Lists
So far, each variable has held a single value. But programs often deal with many values: a shopping list, a class of students, a series of temperatures. A list holds any number of values in order, in a single variable.
Creating a list
Write the items inside square brackets, separated by commas:
fruits = ["apple", "banana", "cherry"] scores = [88, 92, 75, 64] mixed = ["Ada", 36, True, 1.75] empty = [] print(fruits) print(scores) print(mixed) print(empty) print(type(fruits))
A list can hold any types, even a mix. In practice, most lists hold items of the same kind. The items stay in the order you wrote them, and the same value can appear more than once.
len() tells you how many items a list has:
fruits = ["apple", "banana", "cherry"] print(len(fruits))
Indexing and slicing
Lists use the same indexes and slices as strings. The first item is at index 0, and negative indexes count from the end:
fruits = ["apple", "banana", "cherry", "date", "elderberry"] print(fruits[0]) # first print(fruits[2]) print(fruits[-1]) # last print(fruits[1:3]) # a new list print(fruits[:2]) print(fruits[::-1]) # reversed
The difference to notice: an index gives you one item (fruits[0] is the string 'apple'), while a slice always gives you a new list, even if it holds only one item (fruits[0:1] is ['apple']).
As with strings, an index past the end raises an IndexError. A list of 5 items has indexes 0 to 4.
Lists can change
Unlike strings, lists are mutable: you can change them after they're created. Assign to an index to replace an item:
colors = ["red", "green", "blue"] colors[1] = "yellow" print(colors)
colors[1] = "yellow" replaces the item at index 1; the list keeps the same length. You can only replace items that already exist: colors[3] = "pink" on this 3-item list is an IndexError. To add a new item, use the methods in the next section.
Adding items
tasks = ["email Bob", "buy milk"]
# add one item to the end
tasks.append("call mum")
print(tasks)
# add at a position
tasks.insert(0, "wake up")
print(tasks)
# add several items to the end
tasks.extend(["cook", "read"])
print(tasks)| Method | What it does |
|---|---|
append(item) |
adds one item to the end |
insert(index, item) |
puts the item at that index; everything from there on moves one place right |
extend(other_list) |
adds each item of another list to the end |
These methods change the list itself and give back nothing, so you call them on their own line rather than printing them.
A common mix-up: append() with a list adds the whole list as one item, nested inside. Use extend() to add the items one by one:
a = [1, 2] a.append([3, 4]) print(a) b = [1, 2] b.extend([3, 4]) print(b)
You can also join two lists with +:
morning = ["run", "shower"] evening = ["cook", "sleep"] print(morning + evening)
Unlike extend(), + builds a new list and leaves both originals unchanged.
Removing items
pets = ["cat", "dog", "fish", "dog", "hamster"]
# removes the FIRST "dog" only
pets.remove("dog")
print(pets)
# removes the last item and gives it back
last = pets.pop()
print(last, pets)
# removes index 0, gives it back
first = pets.pop(0)
print(first, pets)
# deletes the item at index 0
del pets[0]
print(pets)| Use | When you know | Gives back the item? |
|---|---|---|
remove(value) |
the value to remove | no |
pop() |
nothing: it takes the last item | yes |
pop(index) |
the position | yes |
del items[index] |
the position | no |
pop() is the one to use when you want to remove an item and use it, as with last above.
Removing a value that isn't there raises a ValueError:
pets = ["cat", "dog"]
pets.remove("parrot")Similarly, pop() on an empty list raises an IndexError. To be safe, check first with in (next section).
Searching a list
numbers = [4, 8, 15, 16, 23, 42, 8] # is it in the list? print(15 in numbers) print(99 not in numbers) # position of the first match print(numbers.index(16)) # how many times it appears print(numbers.count(8))
in and not in answer True or False. index() gives the position of the first match, but raises a ValueError if the value isn't there at all, so check with in first when you're not sure. count() simply gives 0 for a missing value.
Sorting
sort() sorts the list in place, which changes the original. sorted() returns a new sorted list and leaves the original alone.
scores = [64, 92, 75, 88] scores.sort() print(scores) scores.sort(reverse=True) print(scores) # sorted() gives back a new list print(sorted([3, 1, 2]))
sort() changes the list and gives back None (Python's "nothing"). So never write scores = scores.sort(): that sorts the list, then replaces it with None:
scores = [64, 92, 75, 88] scores = scores.sort() print(scores)
Use scores.sort() on its own line, or scores = sorted(scores).
| You want | Use | Original list |
|---|---|---|
| to sort the list itself | items.sort() |
changed |
| a sorted copy | sorted(items) |
unchanged |
| largest first | add reverse=True to either |
Sorting only works when the items can be compared with each other: numbers with numbers, strings with strings. Sorting [3, "two", 1] is a TypeError.
reverse() flips the order in place:
steps = [1, 2, 3, 4] steps.reverse() print(steps)
Going deeper: Sorting text optional
Text sorts alphabetically, but all capital letters come before all lowercase letters. To sort ignoring case, give sorted() a key: a function it applies to each item before comparing. str.lower means "compare the lowercase versions":
names = ["Zoe", "adam", "Mia"] print(sorted(names)) print(sorted(names, key=str.lower)) print(names) # unchanged
You'll learn more about key functions in the Lambda, map and filter lesson.
Numbers in lists
Python has built-in functions that work on a whole list of numbers:
temperatures = [21.5, 19.0, 24.3, 22.8, 18.1] print(min(temperatures)) print(max(temperatures)) print(round(sum(temperatures), 1)) # average: total / how many print(round(sum(temperatures) / len(temperatures), 1))
sum() adds up every item, so it only works on lists of numbers. There's no built-in average(): divide the sum() by the len(), as on the last line.
Copying a list
Assigning a list to another variable does not copy it. Remember the label picture from the Variables lesson: alias = original sticks a second label on the same list. Change the list through either name, and both names see the change:
original = [1, 2, 3] alias = original alias.append(4) print(original) # changed too!
To make an independent copy, use copy() or a full slice:
original = [1, 2, 3] copy1 = original.copy() copy2 = original[:] copy1.append(4) print(original) print(copy1)
Going deeper: Lists inside lists optional
A list can contain other lists. That's a simple way to store a grid or a table:
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(grid[0]) # first row
# row 1, column 2: 6
print(grid[1][2])Going deeper: Copying lists inside lists optional
copy() makes a new outer list, but the inner lists are still shared. Changing an inner list through the copy changes the original too:
grid = [[1, 2], [3, 4]] clone = grid.copy() clone[0].append(99) print(grid) # the original changed too!
This is called a shallow copy. To copy everything, all the way down, use deepcopy() from the copy module:
import copy grid = [[1, 2], [3, 4]] clone = copy.deepcopy(grid) clone[0].append(99) print(grid) # unchanged print(clone)
You'll learn more about import in the Modules and Imports lesson.
Converting to and from lists
# string -> list of characters
print(list("hello"))
# string -> list, split at commas
print("a,b,c".split(","))
# list of strings -> one string
print(", ".join(["x", "y", "z"]))
# the numbers 0 to 4
print(list(range(5)))range() gets a full explanation in the For Loops lesson.
Exercises
Exercise 1: Shopping list
Start with an empty list. Add "eggs", "bread" and "milk", then remove "bread" and print the list. It should print ['eggs', 'milk'].
shopping = []
Use append() three times to add the items.
Then call remove("bread").
Exercise 2: Test results
Print the highest score, the lowest score and the average (rounded to 1 decimal place).
scores = [72, 85, 90, 66, 98, 79]
max() and min() work directly on a list.
The average is sum(scores) / len(scores). Round it with round(..., 1).
Exercise 3: Top three
Print the top three scores, highest first: [98, 90, 85]. Don't change the original list.
scores = [72, 85, 90, 66, 98, 79]
sorted(scores, reverse=True) gives a new list, highest first.
Take the first three items with the slice [:3].
Exercise 4: First and last swap
Swap the first and last items of the list, so it prints ['e', 'b', 'c', 'd', 'a'].
letters = ["a", "b", "c", "d", "e"] print(letters)
The first item is letters[0] and the last item is letters[-1].
Swap them in one line: letters[0], letters[-1] = letters[-1], letters[0].
List methods at a glance
A quick reference for later. Each example starts from nums = [3, 1, 2]. The Result column shows what the method gives back, or what nums looks like afterwards for methods that change the list.
| Method | What it does | Example | Result |
|---|---|---|---|
append(x) |
Adds x to the end |
nums.append(4) |
[3, 1, 2, 4] |
extend(items) |
Adds every item from another collection | nums.extend([5, 6]) |
[3, 1, 2, 5, 6] |
insert(i, x) |
Adds x at position i |
nums.insert(0, 9) |
[9, 3, 1, 2] |
remove(x) |
Removes the first x (ValueError if missing) |
nums.remove(1) |
[3, 2] |
pop(i) |
Removes and returns the item at i (the last item if no i) |
nums.pop() |
returns 2, leaves [3, 1] |
clear() |
Removes every item | nums.clear() |
[] |
index(x) |
Position of the first x (ValueError if missing) |
nums.index(2) |
2 |
count(x) |
How many times x appears |
nums.count(3) |
1 |
sort() |
Sorts the list in place | nums.sort(reverse=True) |
[3, 2, 1] |
reverse() |
Reverses the list in place | nums.reverse() |
[2, 1, 3] |
copy() |
Returns a new (shallow) copy | nums.copy() |
[3, 1, 2] |
Built-in functions that work on lists:
| Function | What it does | Example | Result |
|---|---|---|---|
len(lst) |
Number of items | len(nums) |
3 |
min(lst), max(lst) |
Smallest and largest item | max(nums) |
3 |
sum(lst) |
Total of the numbers | sum(nums) |
6 |
sorted(lst) |
A new sorted list (original unchanged) | sorted(nums) |
[1, 2, 3] |
list(items) |
Makes a list from another collection | list("hi") |
['h', 'i'] |
Summary
- A list stores many values in order:
[1, 2, 3]. - Index and slice lists like strings.
len()gives the number of items. - Unlike strings, lists can be changed:
lst[i] = valuereplaces an item. - Add items with
append,insertandextend. Remove them withremove,popanddel. sort()changes the list, whilesorted()returns a new one.min,maxandsumwork on lists of numbers.b = adoesn't copy a list. Usea.copy()instead.
Know something worth teaching? Write your own tutorial with runnable examples and share it.