Lists
A variable holds one value. A list holds many, in order, under one name. Write the items between square brackets, separated by commas. len() tells you how many there are, just as it does for a string.
1streets = ["Mill Lane", "Pond Road", "Hill Street"]2print(streets)3print(len(streets))4mixed = ["Wick", 7, True, 2.5]5print(mixed, len(mixed))6print([], len([]))
['Mill Lane', 'Pond Road', 'Hill Street'] 3 ['Wick', 7, True, 2.5] 4 [] 0
A list can hold any kind of value: numbers, strings, booleans, even a mix. [] is an empty list, with nothing in it yet.
Index and slice
Lists use the same indexes and slices as strings. The first item is at index 0; -1 is the last one. A slice [start:stop] gives a new list, from start up to but not including stop.
1ore = ["coal", "iron", "copper", "gold", "silver"]2print(ore[0])3print(ore[-1])4print(ore[1:3])5print(ore[:2])6print(ore[::-1])
coal silver ['iron', 'copper'] ['coal', 'iron'] ['silver', 'gold', 'copper', 'iron', 'coal']
Ask for an index that does not exist and Python stops with an IndexError. A list of five items has indexes 0 to 4.
1ore = ["coal", "iron", "copper", "gold", "silver"]2print(ore[4])3print(ore[5])
silver
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(ore[5])
IndexError: list index out of rangeLists can change
A string cannot be changed, but a list can. Put a new value at an index with =. To add items, use a list method: append adds one item at the end, insert puts one at an index, extend adds every item from another list.
1houses = ["red", "blue", "green"]2houses[1] = "yellow"3print(houses)4houses.append("white")5print(houses)6houses.insert(0, "black")7print(houses)8houses.extend(["pink", "gray"])9print(houses)
['red', 'yellow', 'green'] ['red', 'yellow', 'green', 'white'] ['black', 'red', 'yellow', 'green', 'white'] ['black', 'red', 'yellow', 'green', 'white', 'pink', 'gray']
These methods change the list itself. They do not make a new one, so there is nothing to assign: write houses.append("white"), not houses = houses.append("white").
What does this print?
1a = [1, 2]2a.append([3, 4])3print(len(a))
append adds exactly one item, even when that item is a list. a becomes [1, 2, [3, 4]], three items. extend([3, 4]) would have given four.
+ joins two lists into a new one, and * repeats a list, just as with strings.
Removing items
There are several ways to take items out. Pick by what you know: the value, or the position.
1tools = ["pick", "lamp", "rope", "map", "lamp"]2tools.remove("lamp")3print(tools)4last = tools.pop()5print(last, tools)6first = tools.pop(0)7print(first, tools)8del tools[0]9print(tools)
['pick', 'rope', 'map', 'lamp'] lamp ['pick', 'rope', 'map'] pick ['rope', 'map'] ['map']
remove(x)deletes the first item equal tox. The second"lamp"stays.pop()takes out the last item and gives it back to you;pop(i)does the same at indexi.del list[i]deletes the item at indexi.clear()empties the whole list.
remove on a value that is not there is an error, a ValueError. Check with in first if you are not sure.
Finding items
in asks "is this value in the list?" and gives True or False. index(x) gives the position of the first x; count(x) says how many times x appears.
1crates = ["iron", "coal", "iron", "gold", "iron"]2print("gold" in crates)3print("silver" in crates)4print(crates.index("gold"))5print(crates.count("iron"))6if "coal" in crates:7 print("Coal found at", crates.index("coal"))
True False 3 3 Coal found at 1
Sorting
sort() puts the list in order, changing the list itself. sorted(list) leaves the list alone and gives you a sorted copy. Both take reverse=True for largest first. Strings sort alphabetically, with capital letters before small ones.
1weights = [7, 2, 9, 4]2print(sorted(weights))3print(weights)4weights.sort(reverse=True)5print(weights)6names = ["wick", "Ada", "bo", "Cy"]7print(sorted(names))
[2, 4, 7, 9] [7, 2, 9, 4] [9, 7, 4, 2] ['Ada', 'Cy', 'bo', 'wick']
What does this print?
1nums = [3, 1, 2]2result = nums.sort()3print(result)
sort() sorts nums in place and gives back nothing, which is None. To get a sorted list as a value, use sorted(nums).
reverse() flips a list in place, without sorting it.
Lists of numbers
sum, min and max, which you met with numbers, also take a list. Together with len they give you an average.
1ore_per_day = [12, 8, 15, 10, 5]2total = sum(ore_per_day)3print("Total:", total)4print("Best day:", max(ore_per_day))5print("Worst day:", min(ore_per_day))6print("Average:", total / len(ore_per_day))
Total: 50 Best day: 15 Worst day: 5 Average: 10.0
Copying a list
b = a does not copy a list. It gives the same list a second name. Change it through one name and you see the change through the other. In lesson 2, a = 9 pointed a at a new value and left b alone; b.append(...) is different, because it changes the one list both names share. Press Step and watch: both names point at one list.
1a = ["lamp", "rope"]2b = a3b.append("map")4print(a)5c = a.copy()6c.append("pick")7print(a)8print(c)
['lamp', 'rope', 'map'] ['lamp', 'rope', 'map'] ['lamp', 'rope', 'map', 'pick']
a.copy() makes a new, separate list with the same items; so does the slice a[:]. Change the copy and the original stays as it was.
Tip: If a list changes "by itself", look for a line like b = a earlier in the program.
Lists and other types
list() turns other things into a list: a string becomes a list of its characters. split turns a string into a list of words, and join glues a list of strings back into one string.
1print(list("lamp"))2words = "coal iron gold".split()3print(words)4print(" + ".join(words))5nums = "4,8,15".split(",")6print(nums)7print(int(nums[0]) + int(nums[1]))
['l', 'a', 'm', 'p'] ['coal', 'iron', 'gold'] coal + iron + gold ['4', '8', '15'] 12
The pieces from split are strings, so convert them with int() before you do math.
Methods at a glance
| Write | What it does |
|---|---|
a.append(x) | adds x at the end |
a.insert(i, x) | puts x at index i |
a.extend(b) | adds every item of b at the end |
a.remove(x) | deletes the first x (ValueError if none) |
a.pop() / a.pop(i) | takes out and gives back the last item / item i |
del a[i] | deletes item i |
a.clear() | deletes everything |
a.index(x) | the position of the first x |
a.count(x) | how many times x appears |
a.sort() / sorted(a) | sorts in place / gives a sorted copy |
a.reverse() | flips the order in place |
a.copy() | a new list with the same items |
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Fix the route
✓Wick's route is in the wrong order and has a stop missing. Change the list so it prints the list below.
['Mill Lane', 'Pond Road', 'Hill Street']
1route = ["Pond Road", "Mill Lane"]2# Your code here3print(route)
Three best days
✓Print the three largest numbers in the list, largest first, without changing ore.
[15, 14, 12]
1ore = [12, 8, 15, 10, 5, 14]2# Your code here
Keep the original
✓This program should keep stock as it was, but the last line shows stock changed. Fix one line.
['coal', 'iron', 'gold'] ['coal', 'iron']
1stock = ["coal", "iron"]2order = stock3order.append("gold")4print(order)5print(stock)
What you learned
- A list holds many values in order:
[1, 2, 3].len()counts them;[]is empty. - Indexes and slices work as for strings; a missing index is an
IndexError. - Lists can change:
a[i] = x,append,insert,extend,remove,pop,del. in,indexandcountfind things;sort()changes the list,sorted()gives a copy.sum,minandmaxwork on lists of numbers.b = ais one list with two names;a.copy()makes a real copy.