More About Lists#
List Access#
In addition to sequence access …
L.append(elem): appendelemto the listL.extend(l): extendLwith another sequencelL.insert(i, elem): insertelemat positioni(same asL[i:i] = elem)L.pop(i): remove element atifrom the list (and return its value)L.sort(): sort the list in place. Elements must be comparable ⟶ careful with mixed lists!L.reverse(): reverses the list in placesorted(L): return a sorted copy of the listreversed(L): returns a reversed copy of the list
List Methods: Examples#
>>> l = [3, 2, 5]
>>> l.append(3)
>>> l
[3, 2, 5, 3]
>>> l.extend([3, 2])
>>> l.sort()
>>> l
[2, 2, 3, 3, 3, 5]
>>> l.reverse()
>>> l
[5, 3, 3, 3, 2, 2]
>>> sorted(l)
[2, 2, 3, 3, 3, 5]
List Comprehension#
The best way to write good code is to write as little code as possible …
Best explained by example#
>>> [i**2 for i in [1, 2, 3]]
[1, 4, 9]
Traditional alternative#
def square_numbers(numbers):
ret = []
for i in numbers:
ret.append(i**2)
return ret
sqn = square_numbers([1,2,3])