CollectionsChapter 24 of 114
Lists
An ordered, changeable run of items - the collection you will use most.
Making a list
Square brackets, items separated by commas:
names = ["Ada", "Grace", "Katherine"]
print(names)
print(len(names))Output
['Ada', 'Grace', 'Katherine'] 3
An empty list is [], and a list can hold anything, including a mix:
empty = []
mixed = [1, "two", 3.0, True, None]
print(empty, len(mixed))Output
[] 5
What makes a list a list
Three properties, and each of them matters:
- Ordered. Items keep the position you put them in.
- Changeable. You can replace, add and remove items in place.
- Duplicates allowed. A list does not care that it holds the same value twice.
scores = [10, 20, 10]
print(scores)
print(scores.count(10))Output
[10, 20, 10] 2
That last point separates a list from a set, which drops duplicates.
Lists from other things
list() turns any sequence into a list:
print(list("abc"))
print(list(range(4)))
print(list((1, 2)))Output
['a', 'b', 'c'] [0, 1, 2, 3] [1, 2]
Nesting
A list can hold lists, which is how you get a grid:
grid = [[1, 2], [3, 4], [5, 6]]
print(grid[0])
print(grid[1][0])
print(len(grid))Output
[1, 2] 3 3
len() counts the outer items, not everything inside.
Testing membership
names = ["Ada", "Grace"]
print("Ada" in names)
print("Alan" in names)Output
True False
Emptiness
An empty list is falsy, so you check it directly:
items = []
if not items:
print("nothing to do")Output
nothing to do
Test yourself
2 questionsWhich is true of a list but not a set?
Show the answer
It keeps duplicates — A set drops duplicates on the way in. A list keeps every item you put in it.
What does len([[1, 2], [3, 4], [5, 6]]) give?
Show the answer
3 — len counts the outer items. It does not look inside them.
List Access
Get items out by position, from either end, and in slices.