Tips and Traps¶
listis essentially a resizable array of objects in Python.Almosts all methods of list are in-place.
list.popis inplace and returns the removed element.To get unique elements in a list, you can first coerce the list to a set and then convert the set back to a list.
unique_list = list(set(alist))To check whether an object
xis a in a listalist, you can usex in alistIf you want to know the position of the element, use a Look Before You Leap (LBYL) style with a conditional expression as below.
i = alist.index(x) if x in alist else None
The list object in Python does not have a
findmethod which is inconvenient. To do a clean "find" in a list in Python, you can use the following style of code.if x in alist: index = alist.index(x)You can use
set(alist)to get unique values of a list. If you want to return a list (rather than a set) of unique values, you can uselist(set(alist)). Another way is to use the methodnumpy.unique.The difference between list and tuple in Python is that a list is mutable while a tuple is immutable. So you can think of tuple as immutable version of list. Tuples can be used in dictionarys in Python as keys while lists cannot.
from operator import itemgetter
Construct a List¶
List Comprehension¶
my_list = [(i, j) for i in range(3) for j in range(i, 3)]
my_list
List with Given Size¶
my_list = [None] * 10
my_list
mylist = [0 for _ in range(10)]
mylist
Size of List¶
len(my_list)
Slicing¶
my_list = [1, 2, 3, 4, 5]
my_list
my_list[2:4]
my_list[8:9]
The [] operator of list accepts only int or slice object,
which makes it inconvenient to get elements at non-consecutive places.
This is similar to numpy arrays.
Fortunately,
you can use the function operator.itemgetter
to extract elements at arbitrary places from a list (or numpy array).
my_list = [1, 2, 3, 4, 5]
my_list
my_list[[1, 3]]
Define a callable object to get elements at index 1 and 3. The callable object is reesuable.
iget = itemgetter(1, 3)
iget(my_list)
Or you can simply chain operators if you only need it once.
itemgetter(1, 3)(my_list)
The in Operator¶
The best way to check whether a value is in a list is to use the in operator.
The count method can also be used but is slower.
The index method cannot be used.
Actually to call the index method of a list,
you'd better first check for existance of element using the in operator.
my_list = [1, 2, 3, 1]
1 in my_list
my_list.count(1)
my_list.index(10)
Equality¶
The == operator checks equality by value.
["a", "b"] == ["a", "b"]
[] == []
() == ()
The is operator checks equality by references.
["a", "b"] is ["a", "b"]
[] is []
Tuple is immutable so there is only a single empty tuple in Python.
() is ()
Concatenate Lists¶
The + operator concatenates 2 lists together and returns a new list.
Notice that the original 2 lists are not changed.
This is different from the methodss list.append and list.prepend
which are in-place.
my_list + [1, 2, 3]
The + operator does not work on collections of different types.
my_list + (1, 2, 3)
List is Mutable¶
A list object is mutable in Python,
thus methods such as append, extend, etc. changes the original list in place.
tuple is the immutable version of list in Python.
my_list = [(i, j) for i in range(3) for j in range(i, 3)]
my_list
my_list.append(1000)
my_list
my_list.extend([2000, 3000])
my_list
Flatten a List¶
You can use the list comprehension or the itertools module to flatten a list.
The list comprehension is preferred for its simplicity.
my_list = [[2, 3], [4, 5, [6, 7, 8, 9, [10]]]]
my_list
[val for sublist in my_list for val in sublist]
import itertools
list(itertools.chain.from_iterable(my_list))
Sort a List¶
Please refer to Sort a List for more details.
Remove Elements from a List¶
The method
removeremoves the first matched value.The method
popremoves an element at the specified index in place and returns the removed element. By default, the last element is removed. The commanddelcan also be used to remove an element at the specified index, however, it sugggested that you avoid usingdeland uselist.popinstead.Assign an element of a list to
Nonedoes NOT remove the corresponding element from the list!
remove¶
x = [4, 3, 2, 1]
x.remove(3)
x
pop¶
x = [4, 3, 2, 1]
print(x.pop(0))
print(x)
x = [4, 3, 2, 1]
print(x.pop())
print(x)
Assign None to Element Won't Remove It¶
x = [1, 2, 3, 4]
x
x[2] = None
x
Insert an Element into a List¶
x = [1, 2, 3, 4]
x.insert(1, 1000)
x
Iterate and Append Elements into a List¶
Suppose you want to iterate through a list,
do some calculation based on the element and then append the calculated value back to the list.
Notice that the following code without the break clause causes dead loop.
x = [1, 2, 3]
for e in x:
if len(x) >= 10:
break
x.append(e)
x
There are multiple ways to fix the issue.
- You can make a copy of the list before looping (which is not recommended).
- You can loop from the back of the list (using
reversed) if order does not matter. - Loop using range (recommended).
x = [1, 2, 3]
for e in reversed(x):
x.append(e)
x
x = [1, 2, 3]
for i in range(len(x)):
x.append(x[i])
x