More About Lists¶
List Access¶
In addition to sequence access …
L.append(elem)
: appendelem
to the listL.extend(l)
: extendL
with another sequencel
L.insert(i, elem)
: insertelem
at positioni
(same asL[i:i] = elem
)L.pop(i)
: remove element ati
from 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 …
>>> [i**2 for i in [1, 2, 3]]
[1, 4, 9]
def square_numbers(numbers):
ret = []
for i in numbers:
ret.append(i**2)
return ret
sqn = square_numbers([1,2,3])