Lists in Python
A list stores an ordered collection of values in one variable, written between square brackets. Items are read by index, starting at 0, and a slice such as items[1:3] gives a new list holding part of them. Lists can be changed after they are created, which sets them apart from strings and tuples.
Key facts
fruits = ["apple", "banana", "cherry"]creates a list of three strings. The square brackets make it a list.- The first item is
fruits[0]and the last isfruits[-1]. Indexes start at 0. fruits[1:3]gives a new list with the items at index 1 and 2. The stop index is never included.- A list can be changed in place, so
fruits[1] = "kiwi"replaces an item. A string cannot. len(fruits)returns the number of items, and"kiwi" in fruitstests whether a value is present.
What is a list in Python?
A list stores an ordered collection of values in one variable. You write the values between square brackets, separated by commas, and Python keeps them in that order. Each value is called an item, and a list is the everyday way to keep related values together, such as the names in a class or the prices in a cart.
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(type(fruits))
print(len(fruits))['apple', 'banana', 'cherry'] <class 'list'> 3
type() reports the value as a list, and len() counts its items. A list is a sequence, like a string, so the indexing and slicing you used on strings work the same way here. Unlike a string, a list can be changed after it is created, and the next lesson covers the methods that add and remove items.
How do I create a list in Python?
Write the items between square brackets. An empty pair of brackets makes an empty list, and one list can mix strings, numbers and booleans. list() builds a list from any iterable, such as a string or a range.
empty = []
mixed = ["Ada", 36, True, 1.75]
letters = list("abc")
numbers = list(range(1, 6))
print(empty)
print(mixed)
print(letters)
print(numbers)[] ['Ada', 36, True, 1.75] ['a', 'b', 'c'] [1, 2, 3, 4, 5]
A list of one type is the common case, because a loop over it can treat every item the same way. The mixed list is legal, and it shows that a list holds values of any type. list("abc") splits the string into one item per character, and list(range(1, 6)) spells out the numbers a range would produce.
How do I access an item in a list by its index?
Put the item's position in square brackets after the list name. Positions are called indexes, or indices in Python's own messages. They start at 0, and a negative index counts from the end, so -1 is the last item.
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[2])
print(fruits[-1])
print(fruits[-3])apple cherry cherry apple
A list of three items has the indexes 0, 1 and 2, and the same items as -3, -2 and -1. Asking for index 3 stops the program with IndexError: list index out of range, the list error you will see most. The index has to be an integer, so fruits["0"] fails too.
How do I slice a list in Python?
Write a start and a stop index with a colon between them. A slice returns a new list holding the items from the start index up to, but not including, the stop index. Leave the start out to begin at the first item, leave the stop out to run to the end, and add a third number to set the step.
nums = [10, 20, 30, 40, 50]
print(nums[1:3])
print(nums[:2])
print(nums[2:])
print(nums[::2])
print(nums[::-1])
print(nums)[20, 30] [10, 20] [30, 40, 50] [10, 30, 50] [50, 40, 30, 20, 10] [10, 20, 30, 40, 50]
The last line proves the original list is untouched, because a slice always builds a new list. nums[::2] takes every second item, and nums[::-1] walks backward, which is the shortest way to reverse a list. The stop rule is the same one range() uses, so nums[1:3] holds two items, not three.
| Slice | Meaning | Example | Result |
|---|---|---|---|
items[start:stop] | From start up to, but not including, stop | nums[1:3] | [20, 30] |
items[:stop] | From the first item up to stop | nums[:2] | [10, 20] |
items[start:] | From start to the end | nums[2:] | [30, 40, 50] |
items[::step] | Every step-th item, so 2 takes every second one, and a negative step walks backward | nums[::-1] | [50, 40, 30, 20, 10] |
items[:] | Every item, as a new list | nums[:] | [10, 20, 30, 40, 50] |
How do I change an item in a list?
Assign a new value to the index. A list is mutable, which means it can be changed in place after it is created, so fruits[1] = "kiwi" replaces the second item without building a new list.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "kiwi"
print(fruits)
fruits[-1] = "mango"
print(fruits)['apple', 'kiwi', 'cherry'] ['apple', 'kiwi', 'mango']
Strings don't allow this. Assigning to one character of a string raises a TypeError, because a string is immutable and every change to it produces a new string. Being mutable is the main difference between a list and a tuple, which the tuples lesson covers.
word = "banana"
word[0] = "c"Traceback (most recent call last):
File "main.py", line 2, in <module>
word[0] = "c"
~~~~^^^
TypeError: 'str' object does not support item assignmentMethods such as append() and remove() add or remove items rather than replace them, and they get their own lesson next.
How do I get the length of a list or check whether it contains a value?
Call len() for the length and use in for the test. len(prices) returns the number of items, and 12 in prices is True when some item equals 12. A for loop visits the items one at a time.
prices = [4.5, 12, 3.25]
print(len(prices))
print(12 in prices)
print(7 in prices)
total = 0
for price in prices:
total = total + price
print(total)3 True False 19.75
The loop adds up the prices the way the for loops lesson did, and sum(prices) does the same in one call. in compares values, not positions, so it can't tell you where the item is. The index() method does that, and the next lesson covers it.
What is a list of lists in Python?
A list of lists is a list whose items are themselves lists. It is also called a nested list, and it is the usual way to hold a grid or a table, with one inner list per row.
grid = [[1, 2, 3], [4, 5, 6]]
print(grid[1])
print(grid[1][0])
print(len(grid))
for row in grid:
print(row)[4, 5, 6] 4 2 [1, 2, 3] [4, 5, 6]
grid[1] is the whole second row, and a second pair of brackets picks an item from it, so grid[1][0] is 4. len(grid) counts the rows, not every number, because the outer list has two items. Looping over the grid gives one row per pass.
Common mistakes with lists in Python
These four mistakes with lists are the common ones. Two stop the program with a message, and two run without complaint and give a wrong result.
- IndexError: list index out of range. The index is too big, often by one, because the last item of a three-item list is at index 2, not 3. Check
len(), or use-1for the last item. - TypeError: list indices must be integers or slices, not str. The index was written as a string, such as
fruits["0"], or came frominput()withoutint()around it. - Changing a copy that isn't a copy.
b = amakes both names point to the same list, so changingbchangesa. Writeb = a[:]to get a separate list, and the next lesson addscopy(), which does the same job. - Counting from 1.
fruits[1]is the second item. The first isfruits[0].
Run the three programs to see the two messages and the shared list, then fix the first two in the editor.
fruits = ["apple", "banana", "cherry"]
print(fruits[3])Traceback (most recent call last):
File "main.py", line 2, in <module>
print(fruits[3])
~~~~~~^^^
IndexError: list index out of rangefruits = ["apple", "banana", "cherry"]
print(fruits["0"])Traceback (most recent call last):
File "main.py", line 2, in <module>
print(fruits["0"])
~~~~~~^^^^^
TypeError: list indices must be integers or slices, not stra = [1, 2, 3]
b = a
b[0] = 99
print(a)
c = a[:]
c[0] = 1
print(a)
print(c)[99, 2, 3] [99, 2, 3] [1, 2, 3]
Exercise
Change the last score from 64 to 70 by assigning to its index, so the program prints [72, 85, 90, 70], then 72, then 4. The starter prints the list unchanged.
scores = [72, 85, 90, 64]
print(scores)
print(scores[0])
print(len(scores))
[72, 85, 90, 70] 72 4
Show the solution
scores = [72, 85, 90, 64]
scores[3] = 70
print(scores)
print(scores[0])
print(len(scores))
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
fruits = ["apple", "banana", "cherry"] print(fruits[1])Indexes start at 0, so index 1 is the second item, banana. Reading index 1 as the first item is the mistake to avoid.
-
2What does this program print?
nums = [10, 20, 30, 40] print(nums[1:3])A slice starts at the start index and stops before the stop index, so 1:3 gives the items at 1 and 2. Including the item at index 3 is the common misreading.
-
3Which expression creates an empty list?
Square brackets with nothing inside make an empty list. Empty curly braces make an empty dictionary, not a set, and empty parentheses make an empty tuple.
-
4What does this program print?
nums = [3, 8, 5] print(nums[-1])A negative index counts from the end, so -1 is the last item, 5. Negative indexes are valid, so there is no error.
-
5What happens when a program runs print(fruits[3]) on a list of three items?
Three items have the indexes 0, 1 and 2, so index 3 is out of range and Python raises IndexError. Python never returns None for a missing index.