Python extend with an empty list bug? [duplicate]
Extend is a method of list, which modifies it but doesn’t return self (returning None instead). If you need the modified value as the expression value, use +, as in [2]+[].
Extend is a method of list, which modifies it but doesn’t return self (returning None instead). If you need the modified value as the expression value, use +, as in [2]+[].
self.myList.extend([0] * (4 – len(self.myList))) This works when padding with integers. Don’t do it with mutable objects. Another possibility would be: self.myList = (self.myList + [0] * 4)[:4]
create subList() Returns a view of the portion of this list between fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of … Read more
That’s what sets (e.g., HashSet<T>) are for. Sets have no defined order, and SetEquals verifies whether the set and another collection contain the same elements. var set = new HashSet<int>(list1); var equals = set.SetEquals(list2);
Use ArrayList.addAll(). Something like this should work (assuming lists contain String objects; you should change accordingly). List<String> combined = new ArrayList<String>(); combined.addAll(firstArrayList); combined.addAll(secondArrayList); combined.addAll(thirdArrayList); Update I can see by your comments that you may actually be trying to create a 2D list. If so, code such as the following should work: List<List<String>> combined2d = new … Read more
startswith and in, return a Boolean. The in operator is a test of membership. This can be performed with a list-comprehension or filter. Using a list-comprehension, with in, is the fastest implementation tested. If case is not an issue, consider mapping all the words to lowercase. l = list(map(str.lower, l)). Tested with python 3.11.0 filter: … Read more
The key in List<T>.slice function is the .toList() at the end, which will create a new List with the elements, using a shallow element copy. For summary: .slice() will create a new List with the shallow copy of the subset of elements; if the original list contains objects, changes to values within the objects will … Read more
Yes, you are right, it is O(n) where n – length of list. Look here for more information: https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
Cleaner Pythonic approach: >>> [(x,y) for x,y in zip(myList, myList[1:]) if y == 9] [(8, 9), (4, 9), (7, 9)] What is the code above doing: zip(some_list, some_list[1:]) would generate a list of pairs of adjacent elements. Now with that tuple, filter on the condition that the second element is equal to 9. You’re done … Read more
A random sample like this returns list of unique items of sequence. Don’t confuse this with random integers in the range. >>> import random >>> random.sample(range(30), 4) [3, 1, 21, 19]