A Python list is an ordered collection of values stored under one name — a shopping list, a set of scores, the lines of a file. Lists are one of the first data structures you learn and one you will use in almost every program. This guide explains Python lists for beginners with short examples you can run.
Creating a list
Put values between square brackets, separated by commas:
fruits = ["apple", "banana", "cherry"]
scores = [72, 88, 95, 61]
empty = []
A list can hold any kind of value — text, numbers, even other lists — and can mix them, although in practice most lists hold one kind of thing.
Getting items out: indexing
Each item has a position called its index. Python counts from zero:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[2]) # cherry
print(fruits[-1]) # cherry (negative counts from the end)
| Item | "apple" | "banana" | "cherry" |
|---|---|---|---|
| Index | 0 | 1 | 2 |
| Negative index | -3 | -2 | -1 |
Asking for fruits[3] gives an IndexError, because a three-item list stops at index 2. It is one of the most common beginner errors; see Python errors beginners make.
Slicing: taking part of a list
A slice takes a range of items with [start:stop]. The stop position is not included:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:3]) # [20, 30]
print(numbers[:2]) # [10, 20] from the start
print(numbers[3:]) # [40, 50] to the end
print(numbers[::-1]) # [50, 40, 30, 20, 10] reversed
Changing a list
Lists are mutable: you can change them after creating them.
fruits = ["apple", "banana"]
fruits.append("cherry") # add to the end
fruits.insert(0, "kiwi") # add at a position
fruits[1] = "mango" # replace an item
print(fruits) # ['kiwi', 'mango', 'banana', 'cherry']
fruits.remove("banana") # remove by value
last = fruits.pop() # remove and return the last item
print(last) # cherry
print(fruits) # ['kiwi', 'mango']
The list tools you will use most
| Code | What it does |
|---|---|
len(items) | How many items |
items.append(x) | Add x to the end |
items.insert(i, x) | Add x at position i |
items.remove(x) | Remove the first x |
items.pop() | Remove and return the last item |
x in items | True if x is in the list |
items.index(x) | Position of the first x |
items.count(x) | How many times x appears |
items.sort() | Sort the list in place |
sorted(items) | Return a new sorted list |
sum(items), min(items), max(items) | Total, smallest, largest (for numbers) |
Looping over a list
The most common thing to do with a list is go through it one item at a time:
scores = [72, 88, 95, 61]
for score in scores:
if score >= 70:
print(f"{score}: pass")
else:
print(f"{score}: retake")
If you need the position too, use enumerate:
tasks = ["email Sam", "buy milk", "call bank"]
for number, task in enumerate(tasks, start=1):
print(f"{number}. {task}")
Building a new list from an old one
A common pattern: start with an empty list and append what you want to keep.
scores = [72, 88, 95, 61]
passed = []
for score in scores:
if score >= 70:
passed.append(score)
print(passed) # [72, 88, 95]
Once that pattern is comfortable, you will meet a shorter form called a list comprehension, which does the same thing in one line:
passed = [score for score in scores if score >= 70]
Learn the long version first; the short one only makes sense once the long one is automatic.
Sorting: sort() versus sorted()
names = ["Zoe", "Ali", "Mia"]
print(sorted(names)) # ['Ali', 'Mia', 'Zoe'] — new list; names unchanged
names.sort() # changes names itself
print(names) # ['Ali', 'Mia', 'Zoe']
A classic trap: names = names.sort() sets names to None, because .sort() changes the list and returns nothing.
Lists vs tuples vs dictionaries
| Type | Looks like | Use when |
|---|---|---|
| List | ["a", "b"] | An ordered collection that can change |
| Tuple | ("a", "b") | A fixed group of values that should not change, such as coordinates |
| Dictionary | {"name": "Sam"} | Looking values up by a name rather than a position |
When you find yourself remembering "position 3 is the phone number", you want a dictionary instead. Our guide to Python dictionaries explained simply picks up from here.
Practise
- Make a list of five numbers and print the largest and the total.
- Ask the user for words until they type
done, then print the words sorted. - Given a list of names, print only those longer than four letters.
Answers to similar drills are in our Python exercises for beginners, and project seven in Python projects for complete beginners — a to-do list — is the natural first project using lists. When you want to reuse list-processing code, Python functions explained is next.
Lists open the part on data structures in Python for Beginners — creation, access and methods — followed by tuples and sets, dictionaries, and JSON, with test questions at the end. The free Practice Toolkit on the book's page has graded exercises for each.
Frequently asked questions
Why do Python lists start at 0?
The index is the distance from the start of the list. The first item is zero steps from the start. Most programming languages count this way.
Can a list contain different types?
Yes, but lists are easier to work with when every item is the same kind of thing.
What is the difference between append() and extend()?
append(x) adds x as one item. extend(other_list) adds each item of another list separately.