CollectionsChapter 34 of 114
List Methods
The full set of list methods, and which return a value rather than None.
The whole list
| Method | Does | Returns |
|---|---|---|
append(x) | add one item at the end | None |
extend(items) | add each item from an iterable | None |
insert(i, x) | put x at position i | None |
remove(x) | drop the first x | None |
pop(i) | drop and hand back the item at i | the item |
clear() | drop everything | None |
index(x) | first position of x | an int |
count(x) | how many x | an int |
sort() | reorder in place | None |
reverse() | flip in place | None |
copy() | a new shallow copy | a list |
The None rule
Eight of the eleven return None, because they change the list in place. This is the single biggest source of list bugs:
names = ["Grace", "Ada"]
print(names.sort())
print(names.append("Zoe"))
print(names)Output
None None ['Ada', 'Grace', 'Zoe']
Both printed None, and both did their job. Call them for the effect; never assign the result.
The three that give you something back
names = ["Ada", "Grace", "Ada"]
print(names.pop())
print(names.index("Grace"))
print(names.count("Ada"))
print(names)Output
Ada 1 1 ['Ada', 'Grace']
reverse versus reversed
reverse() changes the list. reversed() gives you something to loop over and leaves the list alone:
numbers = [1, 2, 3]
numbers.reverse()
print(numbers)
original = [1, 2, 3]
print(list(reversed(original)))
print(original)Output
[3, 2, 1] [3, 2, 1] [1, 2, 3]
The same pairing applies to sort() and sorted(). When a builtin and a method share a name like this, the method changes and the builtin returns.
Functions that take a list
Not methods, but you will reach for them constantly:
numbers = [4, 1, 3]
print(len(numbers))
print(sum(numbers))
print(min(numbers), max(numbers))
print(sorted(numbers))
print(any(n > 3 for n in numbers))
print(all(n > 0 for n in numbers))Output
3 8 1 4 [1, 3, 4] True True
A list as a stack
append() and pop() together make a stack, and both are fast:
stack = []
stack.append("a")
stack.append("b")
print(stack.pop())
print(stack)Output
b ['a']
A list is a poor queue
pop(0) works, but every remaining item shifts down one, so it gets slow on a long list. collections.deque is built for it:
from collections import deque
queue = deque(["a", "b", "c"])
queue.append("d")
print(queue.popleft())
print(list(queue))Output
a ['b', 'c', 'd']
Test yourself
2 questionsWhich list method hands back the item it removed?
Show the answer
pop() — remove takes a value and returns None; pop takes a position and returns the item.
What is the difference between reverse() and reversed()?
Show the answer
reverse() changes the list; reversed() returns something to loop over — The same pairing as sort() and sorted(). The method changes; the builtin returns.
Tuples
An ordered sequence that cannot change, and why that is useful.