After this lesson you can store many values in one variable, pick out any of them by position, change them, and walk through them one by one. Lists are the collection you will use most in Python, so it is worth getting comfortable with them early.
What a list is
A variable holds one value. Often you have many related values: the prices in a shop, the names in a class, the books on a shelf. A list keeps them together, in order, under one name. You write a list with square brackets and commas:
prices = [250, 99, 1200, 75]
names = ["Asha", "Ben", "Chloe"]
mixed = [1, "two", 3.0, True]
empty = []
print(prices)
print(names)
print(mixed)
print(empty)
print(type(prices))[250, 99, 1200, 75]
['Asha', 'Ben', 'Chloe']
[1, 'two', 3.0, True]
[]
<class 'list'>A list can hold any kind of value, even a mix, though in practice most lists hold values of one kind. The empty list [] is a perfectly good list. It is where you start when you plan to add items later.
Use len() to count the items:
print(len(prices))
print(len(empty))4
0Reading items by index
Every item has a position called an index. Python counts from zero, so the first item is at index 0, the second at index 1, and so on.
print(names[0])
print(names[1])
print(names[2])Asha
Ben
ChloeNegative indexes count from the end. This is handy because you do not need to know the length: -1 is always the last item and -2 the one before it.
print(names[-1])
print(names[-2])Chloe
BenAsking for a position that does not exist is an error:
print(names[3])IndexError: list index out of rangeA list with three items has valid indexes 0, 1 and 2 (and -1, -2, -3). Index 3 is one too far.
Slicing
A slice takes a part of a list and gives you a new list. The form is items[start:stop]. The item at start is included, the item at stop is not.
shelf = ["Python", "SQL", "HTML", "CSS", "Git", "Linux"]
print(shelf[1:4])
print(shelf[:2])
print(shelf[3:])
print(shelf[-2:])
print(shelf[::2])['SQL', 'HTML', 'CSS']
['Python', 'SQL']
['CSS', 'Git', 'Linux']
['Git', 'Linux']
['Python', 'HTML', 'Git']Leaving out start means "from the beginning", leaving out stop means "to the end", and a third number is the step. shelf[::2] takes every second item. If you have already met slicing on strings, it works the same way here. Slicing never raises an error for out-of-range numbers; it just gives you as much as exists.
Changing a list
Strings cannot be changed after they are made, but lists can. We say a list is mutable. Assign to an index to replace an item, or to a slice to replace several:
scores = [40, 55, 61, 78]
scores[0] = 45
print(scores)
scores[1:3] = [56, 62, 63]
print(scores)[45, 55, 61, 78]
[45, 56, 62, 63, 78]The second assignment replaced two items with three, so the list grew by one. You will meet the usual ways to add and remove items, such as append and remove, in the next lesson.
Looping over a list
The for loop was made for lists. It gives you each item in turn:
total = 0
for price in prices:
total = total + price
print(total)1624When you also need the position, use enumerate:
for position, name in enumerate(names, start=1):
print(position, name)1 Asha
2 Ben
3 ChloePython also has the built-in sum, min and max, which work on a list of numbers, and the in operator to test membership:
print(sum(prices), min(prices), max(prices))
print(99 in prices)
print("Zed" in names)1624 75 1200
True
FalseTwo names, one list
This is the idea that surprises almost everyone once. Assigning a list to another name does not copy the list. Both names point at the same list.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)
print(a is b)[1, 2, 3, 4]
[1, 2, 3, 4]
TrueChanging the list through b changed what a sees, because there is only one list. When you want an independent copy, ask for one:
c = a.copy()
c.append(5)
print(a)
print(c)[1, 2, 3, 4]
[1, 2, 3, 4, 5]a[:] and list(a) also make a shallow copy. "Shallow" matters when a list holds other lists, which the lesson on nested collections explains.
Common mistakes
- Counting from 1. The first item is
items[0]. The last isitems[len(items) - 1], or simplyitems[-1]. - Reading past the end.
items[len(items)]always fails. Check the length first, or loop over the items instead of indexing. - Expecting
b = ato copy. It does not. Usea.copy()when you need a second list. - Changing a list while looping over it. Adding or removing items inside a
forloop over the same list makes the loop skip items. Loop over a copy, or build a new list. - Forgetting that a slice stops early.
items[0:3]has three items, not four. The stop index is not included.
Exercise
Make a list called temps holding 21, 24, 19, 25, 23. Print the first and last items, then print the middle three using a slice, and finally print the highest value.
Show one possible answer
temps = [21, 24, 19, 25, 23]
print(temps[0], temps[-1])
print(temps[1:4])
print(max(temps))21 23
[24, 19, 25]
25A video version of this topic is in the video course at /learn/python/. Next, the list methods lesson shows how to add, remove and rearrange items.
Key points
- A list is an ordered, changeable collection written with square brackets, such as [10, 20, 30].
- Items are read by index starting at 0. Negative indexes count from the end, so -1 is the last item.
- A slice like items[1:3] gives a new list. The start is included and the stop is not.
- Lists are mutable. Assigning to a name copies the reference, not the list, so use items.copy() or items[:] for a real copy.