Chapters
Python114 chapters

CollectionsChapter 34 of 114

List Methods

The full set of list methods, and which return a value rather than None.

The whole list

MethodDoesReturns
append(x)add one item at the endNone
extend(items)add each item from an iterableNone
insert(i, x)put x at position iNone
remove(x)drop the first xNone
pop(i)drop and hand back the item at ithe item
clear()drop everythingNone
index(x)first position of xan int
count(x)how many xan int
sort()reorder in placeNone
reverse()flip in placeNone
copy()a new shallow copya 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:

Python
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

Python
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:

Python
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:

Python
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:

Python
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:

Python
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 questions

Which 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.

Next chapter

Tuples

An ordered sequence that cannot change, and why that is useful.