In Mr. Darto's kitchen there is an order rail (a bar that holds paper slips with clips). Each order is written on a slip of paper and clipped to the rail, side by side. The leftmost clip is number 0, the next one is number 1, and so on. Mr. Darto can clip a new slip at the end, pull the last one off, or rearrange them. The rail stays the same. Only the slips on it change.
Python has a container that works like that rail. It is called a list: an ordered row of values stored in one variable. In the string lesson, the tiles on the menu board were glued in place and could not change. A list is different: you can replace, add and remove its items.
Creating a list
Here are three lists, and some ways to check what they hold:
orders = ["coffee with milk", "sweet tea", "toast"]
prices = [15, 5, 12]
empty = []
print(orders) # ['coffee with milk', 'sweet tea', 'toast']
print(len(orders)) # 3
print("sweet tea" in orders) # True
- A list is written in square brackets
[ ], with commas between its values. Each value is called an item: one slip on the rail.[]alone is an empty list. - Items can be of any type: text, numbers, even a mix. Usually one list holds one kind of data.
printwrites a list with square brackets and single quotes, even though you wrote double quotes in the code.len(orders)counts the items: 3."sweet tea" in orderschecks whether that item is in the list. The result isTrueorFalse.
Indexes and negative indexes
Like the characters of a string, every item has a position number. That number is called its index, like the clip numbers on the rail:
| Item | coffee with milk |
sweet tea |
toast |
|---|---|---|---|
| Index | 0 | 1 | 2 |
| Negative index | -3 | -2 | -1 |
orders[0]iscoffee with milk. Indexes start at 0, so the last item is at indexlen(orders) - 1, which is 2.- Negative indexes count from the back:
orders[-1]istoast,orders[-2]issweet tea. In the listnumbers = [10, 20, 30, 40, 50],numbers[-2]is40, the second item from the end. - Python refuses an index that does not exist:
Traceback (most recent call last):
File "/home/darto/stall.py", line 2, in <module>
print(orders[3])
~~~~~~^^^
IndexError: list index out of range
The ~~~~~~ marks the list, and the ^^^ marks the wrong index. This list only has indexes 0 to 2 (or -1 to -3). So orders[3] and orders[-4] both give an IndexError.
Changing a list
A list is mutable: you can change its contents without making a new list. You can replace one item through its index. For example, after orders[1] = "iced tea" the list is ['coffee with milk', 'iced tea', 'toast'] right away. There are also methods (functions that belong to the list, called with a dot) that change its contents:
orders = ["coffee with milk", "sweet tea", "toast"]
orders.append("iced orange") # add at the end
orders.insert(0, "water") # insert at index 0
orders.pop() # pull off the last item
orders.remove("sweet tea") # drop an item by its value
print(orders) # ['water', 'coffee with milk', 'toast']
This table shows the list after each line:
| Line | What orders holds afterwards |
|---|---|
append("iced orange") |
['coffee with milk', 'sweet tea', 'toast', 'iced orange'] |
insert(0, "water") |
['water', 'coffee with milk', 'sweet tea', 'toast', 'iced orange'] |
pop() |
['water', 'coffee with milk', 'sweet tea', 'toast'] |
remove("sweet tea") |
['water', 'coffee with milk', 'toast'] |
.append(x)adds one item at the right end..insert(i, x)inserts an item at indexi. The items after it move to the right..pop()pulls off the last item and returns it, so you can store it:x = orders.pop()..pop(0)pulls off the first item..remove(x)removes the first item whose value isx..extend(other_list)adds every item of another list, one by one, at the right end.orders.extend(["iced orange", "iced tea"])adds two items.
There are two ways to sort:
prices = [15, 5, 12]
print(sorted(prices)) # [5, 12, 15]
print(prices) # [15, 5, 12], unchanged
prices.sort()
print(prices) # [5, 12, 15]
sorted(prices)makes a new sorted list. The original list does not change.prices.sort()sorts the list itself. A list of text is sorted alphabetically, for exampleapple,banana,bonus,cherry.- The methods that change a list (
append,insert,remove,sort) do not return the list. They returnNone, the empty value from the variables lesson.
Slicing: cutting a list
Slicing takes a part of a list:
orders = ["coffee with milk", "sweet tea", "toast", "iced orange", "water"]
print(orders[:3]) # ['coffee with milk', 'sweet tea', 'toast']
print(orders[1:3]) # ['sweet tea', 'toast']
print(orders[-2:]) # ['iced orange', 'water']
print(orders[::2]) # ['coffee with milk', 'toast', 'water']
print(orders[::-1]) # ['water', 'iced orange', 'toast', 'sweet tea', 'coffee with milk']
- The full form is
list[start:stop:step]. Slicing stops beforestop, exactly like slicing a string. - In the list
data = [1, 2, 3, 4, 5],data[:3]is the same asdata[0:3]: the first three items (indexes 0, 1, 2), which is[1, 2, 3]. [::2]uses a step of 2, so it takes every second item: indexes 0, 2, 4.[::-1]reverses the order.- The result of slicing is always a new list. The original list is not cut, and slicing never gives an
IndexError.
Two names, one list
Guess first: a = ["coffee with milk", "sweet tea"], then b = a, then a.append("toast"). If you print b, does it hold 2 items or 3?
Remember the variables lesson: a name is a label attached to a value. b = a does not copy the list. It puts a second label on the same list:
a = ["coffee with milk", "sweet tea"]
b = a
a.append("toast")
print(b) # ['coffee with milk', 'sweet tea', 'toast']
a and b are one order rail with two labels. A slip that is clipped on through a can also be seen through b. So it prints 3 items.
If you need a separate copy, use .copy() or a full slice a[:]:
a = ["coffee with milk", "sweet tea"]
b = a.copy()
a.append("toast")
print(a) # ['coffee with milk', 'sweet tea', 'toast']
print(b) # ['coffee with milk', 'sweet tea']
Two names for one list also happen when you send a list to a function: the parameter is only another label for the same list. If a function with the parameter items calls items.append("bonus"), the caller's list gets the new item too.
⚠️ A list that turns into None, or changes without you noticing
- Storing the result of
.sort().orders = orders.sort()makesordersholdNone. The next line that takes an item, for exampleorders[0], fails:TypeError: 'NoneType' object is not subscriptable. Callorders.sort()without storing its result, or usein_order = sorted(orders). - Using
lenas the last index. A list with 3 items only goes up to index 2.orders[len(orders)]givesIndexError: list index out of range. For the last item, useorders[-1]. - Thinking
b = amakes a copy. In factaandbare two labels for one list. Copy witha.copy()ora[:]. - Using
appendto join two lists.a = [1], thena.append([2, 3]), makesahold[1, [2, 3]]: one new item that is a list inside the list. To add the items one by one, usea.extend([2, 3]), soaholds[1, 2, 3]. - Removing an item that is not there. If
iced orangeis not in the list,orders.remove("iced orange")fails withValueError: list.remove(x): x not in list. Check first withif "iced orange" in orders:.
TL;DR: A list is an ordered row inside [ ]. len() counts its items, and in checks whether a value is in it. Indexes (position numbers) start at 0, negative indexes count from the back (numbers[-2] is the second item from the end), and an index out of range gives IndexError: list index out of range. Lists are mutable (their contents can change): .append(x) adds at the end, .insert(i, x) inserts at index i, .pop() removes the last item, and .remove(x) removes by value. .sort() sorts the list itself and returns None, while sorted() makes a new list. Slicing [start:stop:step] stops before stop and always makes a new list: data[:3] is the first three items. b = a puts a second label on the same list, so a change through a shows in b. For a separate copy, use .copy() or [:].
⚡ A numbered row
Write:
orders = ["coffee with milk", "sweet tea", "toast"]
print(len(orders)) # 3
print("sweet tea" in orders) # True
Guess first: in numbers = [10, 20, 30, 40, 50], what is numbers[-2]?
40, the second item from the end. Negative indexes count from the right end: -1 is the last item.
Meaning: A list is written with [ ], with commas between its items. len counts the items, and in checks whether a value is in the list. Indexes start at 0, so orders[0] is coffee with milk. An index that doesn't exist gives an IndexError.
⚡ Its contents can change
Write:
orders = ["coffee with milk", "sweet tea", "toast"]
orders.append("iced orange") # add at the end
orders.insert(0, "water") # insert at index 0
orders.pop() # pull off the last item
orders.remove("sweet tea") # drop an item by its value
print(orders) # ['water', 'coffee with milk', 'toast']
Meaning: A list is mutable: you can change its contents without making a new list. .sort() also sorts the list itself, while sorted() makes a new list.
⚡ Cutting a list
Meaning: Slicing with list[start:stop] takes a part of a list and stops before stop, just like slicing a string. For a list called data, data[:3] is the same as data[0:3]: the first three items. The result is always a new list.
⚡ Two names, one list
Guess first: a holds 2 items. b = a, then a.append("toast"). How many items does b hold now?
3 items. b = a doesn't copy the list. It only puts a second label on the same list.
Meaning: If you need a separate copy, use a.copy() or a[:].