Python Lists
What you will learn
- What a list is and the ways to create one
- How to read items with an index, including negative indexes
len,in,+and*with lists- How to loop, compare and unpack a list
- How a list differs from a string and a tuple
1. What is a list?
A list (type list) is an ordered collection of items. You write it with square brackets, with the items separated by commas:
nums = [10, 20, 30, 40]
empty = []
mixed = [1, "two", 3.0, True, None, [5, 6]]
print(nums, type(nums), len(nums))
print(empty, len(empty))
print(mixed)
[10, 20, 30, 40] <class 'list'> 4
[] 0
[1, 'two', 3.0, True, None, [5, 6]]
- Lists keep the order in which you put the items.
- A list can hold any types together, even other lists.
- A list can be changed after it is made: it is mutable (lesson 2.6).
- The same value may appear many times.
Quick check: how many items are in `[1, [2, 3], 4]`?
3. The inner list [2, 3] counts as one item.
2. Creating lists
Besides writing the items out, you can build a list from other collections with list():
print(list())
print(list("abc"))
print(list(range(4)))
print(list((1, 2)))
print(list({"k": 1}))
[]
['a', 'b', 'c']
[0, 1, 2, 3]
[1, 2]
['k']
list("abc") gives the characters, list(range(4)) the numbers, and list(dict) gives the keys. Text can be cut into a list of words with split (lesson 4.4):
words = "the quick brown fox".split()
print(words, len(words))
['the', 'quick', 'brown', 'fox'] 4
3. Indexing
Each item has a position, called its index, counted from 0, exactly as in strings (lesson 4.2). A negative index counts from the end:
nums = [10, 20, 30, 40]
print(nums[0], nums[1], nums[-1], nums[-2])
10 20 40 30
| Item | 10 | 20 | 30 | 40 |
|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 |
| Negative index | -4 | -3 | -2 | -1 |
Items that are lists themselves are reached with a second index:
mixed = [1, "two", 3.0, True, None, [5, 6]]
print(mixed[5], mixed[5][0], mixed[-1][-1])
[5, 6] 5 6
An index that is outside the list raises an error, and so does one of the wrong type:
nums[4]
IndexError: list index out of range
nums["a"]
TypeError: list indices must be integers or slices, not str
An empty list has no valid index: [][0] is an IndexError.
4. Length and membership
print(len(nums), len([]), len([[1, 2], [3]]))
print(20 in nums, 25 in nums, 25 not in nums)
4 0 2
True False True
lencounts the top-level items:[[1, 2], [3]]has2.inandnot intest for membership (lesson 5.1). Python looks at the items one by one, so it can be slow on a very long list.
5. Joining and repeating
+ joins two lists into a new list, and * repeats a list:
print([1, 2] + [3])
print([0] * 5)
print(["a", "b"] * 2)
[1, 2, 3]
[0, 0, 0, 0, 0]
['a', 'b', 'a', 'b']
+ joins lists with lists only:
[1, 2] + 3
TypeError: can only concatenate list (not "int") to list
To add one item, put it in a list ([1, 2] + [3]) or use append (lesson 7.2). A list and a tuple cannot be joined either: [1, 2] + (3,) is a TypeError. Be careful with * on lists that hold other lists; lesson 7.5 explains the trap.
6. Totals and extremes
The built-ins from lesson 3.3 work on lists of numbers, and min, max and sorted also work on text:
print(min(nums), max(nums), sum(nums), sum(nums) / len(nums))
print(sorted(nums, reverse=True))
print(max(["b", "a"]))
10 40 100 25.0
[40, 30, 20, 10]
b
7. Looping
Loop over the items, or over positions and items with enumerate (lesson 6.6):
for n in nums:
print(n, end=" ")
print()
for i, n in enumerate(nums):
print(i, n, end="; ")
print()
10 20 30 40
0 10; 1 20; 2 30; 3 40;
8. Comparing
Lists are equal when they have the same items in the same order. Order comparisons work item by item from the left (lesson 5.1):
print([1, 2, 3] == [1, 2, 3], [1, 2] == [2, 1])
print([1, 2] < [1, 3], [1, 2] != [1, 2])
True False
True False
9. Unpacking
A list can be unpacked into names. The number of names must match, unless you collect the rest with a starred name (lesson 2.1):
first, second, *rest = nums
print(first, second, rest)
a, b = [1, 2]
print(a, b)
10 20 [30, 40]
1 2
A mismatch is an error: x, y = [1, 2, 3] raises ValueError: too many values to unpack (expected 2).
10. Lists and truth
An empty list counts as false, and any other list as true, even [0] or [[]] (lesson 5.3). This gives the usual test for "is there anything in it?":
empty = []
if not empty:
print("empty list is false")
empty list is false
11. List, string or tuple?
list |
str |
tuple |
|
|---|---|---|---|
| written | [1, 2] |
"ab" |
(1, 2) |
| items | anything | characters only | anything |
| can change in place | yes | no | no |
indexing, slicing, len, in, loops |
yes | yes | yes |
Lists and tuples are both sequences of items, but a tuple is fixed (chapter 8).
Worked example: a shopping list
Keep a list of items, show how many there are, and check whether something is on it.
shopping = ["rice", "salt", "oil", "tea"]
print(f"{len(shopping)} items")
print("first:", shopping[0], "| last:", shopping[-1])
print("oil" in shopping, "sugar" in shopping)
for n, item in enumerate(shopping, start=1):
print(f"{n}. {item}")
4 items
first: rice | last: tea
True False
1. rice
2. salt
3. oil
4. tea
| Tool | What it did |
|---|---|
len |
counted the items |
[0] and [-1] |
got the first and the last |
in |
checked membership |
enumerate(..., start=1) |
numbered the lines |
The items are made up.
Common mistakes
- Counting from 1. The first index is
0; the last valid index islen(lst) - 1. - Using an index outside the list, which gives
IndexError. - Joining a list with a single item. Use
lst + [item]orappend. - Thinking
len([[1, 2], [3]])is3. Nested lists count as single items. - Forgetting that an empty list is false.
Key takeaways
- A list is an ordered, changeable collection written with square brackets; its items can be of any type.
- Create one by writing items, with
list(...), or from text withsplit(). - Indexes start at
0; negative indexes count from the end; an invalid index raisesIndexError. len,in,+,*,==,min,maxandsumwork on lists;+joins lists only with lists.- An empty list is false; lists can be unpacked into names.
Practice
1. With fruits = ["fig", "kiwi", "plum"], what are fruits[0], fruits[-1] and len(fruits)?
Show answer
"fig", "plum" and 3.
2. What does [1, 2] + [3, 4] give? And [0] * 3?
Show answer
[1, 2, 3, 4] and [0, 0, 0].
3. What error does [1, 2, 3][3] cause?
Show answer
IndexError: list index out of range. The valid indexes are 0, 1 and 2.
4. Turn the text "3 5 8" into the list of numbers [3, 5, 8].
Show answer
[int(x) for x in "3 5 8".split()] or list(map(int, "3 5 8".split())).
5. Write a check that prints no items when a list cart is empty.
Show answer
if not cart:
print("no items")
6. Unpack [7, 8, 9] so that a is 7 and rest is [8, 9].
Show answer
a, *rest = [7, 8, 9].