Chapters
Python114 chapters

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:

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

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

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

Python
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

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

Python
items = []
if not items:
    print("nothing to do")

Output

nothing to do

Test yourself

2 questions

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

Next chapter

List Access

Get items out by position, from either end, and in slices.