Learn Lists in Python

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…

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

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
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']

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]

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']

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

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[:].

What you will learn