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.
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 slice is a new list print(fruits[:2]) print(fruits[::-1]) # reversed copy
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)
Adding items
tasks = ["email Bob", "buy milk"]
tasks.append("call mum") # add to the end
print(tasks)
tasks.insert(0, "wake up") # add at a position
print(tasks)
tasks.extend(["cook", "read"]) # add several items
print(tasks)You can also join two lists with +:
morning = ["run", "shower"] evening = ["cook", "sleep"] print(morning + evening)
Removing items
pets = ["cat", "dog", "fish", "dog", "hamster"]
pets.remove("dog") # removes the FIRST matching value
print(pets)
last = pets.pop() # removes and returns the last item
print(last, pets)
first = pets.pop(0) # removes and returns the item at an index
print(first, pets)
del pets[0] # deletes by index
print(pets)Removing a value that isn't there raises a ValueError:
pets = ["cat", "dog"]
pets.remove("parrot")Searching a list
numbers = [4, 8, 15, 16, 23, 42, 8] print(15 in numbers) # is it in the list? print(99 not in numbers) print(numbers.index(16)) # position of the first match print(numbers.count(8)) # how many times it appears
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) print(sorted([3, 1, 2])) # sorted() gives back a new list
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)) print(round(sum(temperatures) / len(temperatures), 1)) # average
Copying a list
Assigning a list to another variable does not copy it. Both names point to the same list:
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
print(grid[1][2]) # row 1, column 2 -> 6Going 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
print(list("hello")) # string -> list of characters
print("a,b,c".split(",")) # string -> list
print(", ".join(["x", "y", "z"])) # list of strings -> string
print(list(range(5))) # numbers 0 to 4Exercises
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.