Lists: keeping many values together
Store many values in one Python list, read items by index, add and remove items, check membership with in, and sort, slice and measure lists.
🎯 By the end of this lesson you will be able to:
- Create a list and read items by their index
- Add, change and remove items
- Use len(), in, sorted(), sum(), min(), max() and slices
Outline
What you'll learn and why it matters
A variable holds one value. But a shopping list, a class register or a month of temperatures has many values. Making item1, item2, item3... would be painful. A list keeps many values together, in order, under one name. Lists and loops (next lesson) are where programming starts to save you real time.
Creating a list and reading items
Write a list with square brackets, putting commas between the items:
fruits = ["mango", "banana", "apple"]
print(fruits)
print(fruits[0])
print(fruits[2])
print(fruits[-1])
print(len(fruits))Output
['mango', 'banana', 'apple'] mango apple apple 3
Just like characters in a string (lesson 4), list items are numbered from 0. So a list of 3 items has indexes 0, 1 and 2, and fruits[-1] is always the last item. len() tells you how many items there are.
Adding, changing and removing items
Unlike strings, lists can be changed after you create them.
| Code | What it does |
|---|---|
fruits.append("guava") | Adds an item to the end |
fruits.insert(0, "kiwi") | Adds an item at a position |
fruits[1] = "papaya" | Replaces the item at index 1 |
fruits.remove("apple") | Removes the first item equal to "apple" |
fruits.pop() | Removes and gives you the last item |
cart = ["notebook", "pen"]
cart.append("water bottle")
print(cart)
cart[1] = "gel pen"
print(cart)
cart.remove("notebook")
print(cart)Output
['notebook', 'pen', 'water bottle'] ['notebook', 'gel pen', 'water bottle'] ['gel pen', 'water bottle']
Checking whether something is in a list
in asks whether a value is in a list and gives True or False, so it fits perfectly in an if:
invited = ["Asha", "Ravi", "Meera"]
guest = "Ravi"
if guest in invited:
print(f"Welcome, {guest}!")
else:
print("Sorry, you are not on the list.")Output
Welcome, Ravi!
Lists of numbers
Python has built-in functions that work on whole lists of numbers:
temperatures = [31, 29, 34, 33, 28]
print("Highest:", max(temperatures))
print("Lowest:", min(temperatures))
print("Total:", sum(temperatures))
print("Average:", sum(temperatures) / len(temperatures))
print("Sorted:", sorted(temperatures))Output
Highest: 34 Lowest: 28 Total: 155 Average: 31.0 Sorted: [28, 29, 31, 33, 34]
sorted() gives you a new sorted list and leaves the original unchanged. If you want to sort the list itself, use temperatures.sort().
Slices: taking part of a list
A slice takes a range of items: list[start:stop]. It includes start but stops *before* stop.
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(days[0:5])
print(days[5:])
print(days[:3])Output
['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] ['Sat', 'Sun'] ['Mon', 'Tue', 'Wed']
Leave out start to begin at the front, or leave out stop to go to the end. Slices work on strings too: "Python"[0:3] is "Pyt".
Practice
Guided exercise
Weekly marks
Create a list of five test marks: 72, 85, 64, 90, 78. Print the highest mark, the lowest mark and the average rounded to 1 decimal place. Then add a sixth mark of 88 and print how many marks there are now.
- Create
marks = [72, 85, 64, 90, 78]. - Use
max(),min(), andsum() / len()withround(..., 1). - Use
marks.append(88), thenlen(marks).
Show the solution
marks = [72, 85, 64, 90, 78]
print("Highest:", max(marks))
print("Lowest:", min(marks))
print("Average:", round(sum(marks) / len(marks), 1))
marks.append(88)
print("Number of marks:", len(marks))Output
Highest: 90 Lowest: 64 Average: 77.8 Number of marks: 6
How to get there: The five marks add up to 389, and 389 ÷ 5 = 77.8. After append, the list has 6 items.
Your turn
To-do list
Start with todo = ["pay bill", "call mum", "study Python"]. Remove "call mum", add "buy rice" at the end, and print the first item and the whole list.
Show the solution
todo = ["pay bill", "call mum", "study Python"]
todo.remove("call mum")
todo.append("buy rice")
print(todo[0])
print(todo)Output
pay bill ['pay bill', 'study Python', 'buy rice']
How to get there: remove() deletes by value and append() adds to the end. The first item, at index 0, is still "pay bill".
Common mistakes
colours = ["red", "green", "blue"]
print(colours[3])Python stops with this error
IndexError: list index out of range
Using index 3 for the third item
You see: IndexError: list index out of range, or the wrong item
Fix: Indexes start at 0, so the third item is [2]. The last item is always [-1].
Writing cart = cart.append(x)
You see: cart becomes None and later code fails
Fix: Just write cart.append(x); it changes the list in place.
Removing an item that is not there
You see: ValueError: list.remove(x): x not in list
Fix: Check with if x in cart: before cart.remove(x).
Forgetting commas between items
You see: SyntaxError: invalid syntax. Perhaps you forgot a comma?
Fix: Separate every item with a comma.
Recap
- A list holds many values in order:
fruits = ["mango", "banana"]. - Read items by index from 0;
[-1]is the last item andlen()counts the items. append,insert,removeandpopchange the list itself.- Use
into check membership, andsum,min,max,sortedand slices to work with whole lists.
Key terms
- List
- An ordered collection of values written in square brackets.
- Slice
- Part of a list or string, written list[start:stop]; stop is not included.
- None
- Python's value meaning "nothing".
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. `nums = [10, 20, 30, 40]`. What is `nums[1]`?
2. What does `["a", "b", "c", "d"][1:3]` give?
3. How do you add "tea" to the end of the list `drinks`?
4. What does `"kiwi" in ["apple", "kiwi"]` give?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.