← All lessons
Python basics · Lesson 9 of 10

Lists

A variable holds one value. A list holds many, in order, inside square brackets with commas between: [3, 8, 5]. Lists can hold numbers, strings, anything, and they can grow and shrink while the program runs.

scores = [70, 85, 92]
names = ["Ana", "Ben", "Cy"]
empty = []
print(scores)
print(len(names))
Prints
[70, 85, 92]
3

Each item has an index, starting at 0, just like the characters of a string. names[0] is the first item, names[-1] the last. You can also change an item by assigning to its index.

names = ["Ana", "Ben", "Cy"]
print(names[1])
names[1] = "Bea"
print(names)
Prints
Ben
['Ana', 'Bea', 'Cy']

A slice takes a piece of a list: items[1:3] gives the items at indexes 1 and 2 (it stops before 3, like range). Leave a side out to go from the start or to the end. Slices work on strings too.

nums = [10, 20, 30, 40, 50]
print(nums[1:3])
print(nums[:2])
print(nums[3:])
print("python"[0:3])
Prints
[20, 30]
[10, 20]
[40, 50]
pyt

Lists have methods for changing them. append(x) adds x at the end, insert(i, x) puts x at index i, remove(x) takes out the first x, and pop() removes the last item and gives it back. Unlike string methods, these change the list itself. x in my_list asks whether x is in it.

basket = ["egg"]
basket.append("milk")
basket.append("bread")
basket.remove("egg")
last = basket.pop()
print(basket, last)
print("milk" in basket)
Prints
['milk'] bread
True

A for loop goes through a list item by item. Python also has built-in functions for the common jobs: sum(), max(), min() and sorted(), which gives back a sorted copy. my_list.sort() sorts the list itself instead.

temps = [18, 23, 15, 21]
for t in temps:
    if t > 20:
        print(t, "is warm")
print(sum(temps) / len(temps))
print(max(temps), sorted(temps))
Prints
23 is warm
21 is warm
19.25
23 [15, 18, 21, 23]

Asking for an index that doesn't exist (index 5 of a five-item list) stops with an IndexError.

Practice

What does this print?

colors = ["red", "green", "blue"]
print(colors[2])
More info

Quick reference

[a, b, c]A list. [] is an empty one.
items[i], items[-1]The item at index i (from 0), the last item.
items[a:b]A slice: from index a up to, not including, b.
append insert remove popAdd at the end, add at an index, remove a value, remove and return the last.
x in itemsTrue if x is in the list.
len sum max min sortedBuilt-in functions for lists.

Related courses