← All lessons
Programming basics · Lesson 5 of 9

Lists

A list holds several values in order, written in square brackets: scores = [8, 5, 9]. Lists can hold anything, including text and other lists, and they can grow and shrink.

Each item has a position called its index, and indexes start at 0, not 1. scores[0] is the first item, scores[2] the third. Negative indexes count from the end: scores[-1] is the last. len(scores) says how many items there are.

fruit = ["apple", "pear", "fig"]
print(fruit[0])
print(fruit[-1])
print(len(fruit))
Prints
apple
fig
3

Lists can change. append(x) adds x at the end, fruit[1] = "plum" replaces an item, remove(x) takes the first x out, and x in fruit asks whether it's there.

A slice takes part of a list: nums[1:3] gives the items at index 1 and 2 (it stops before 3, like range). Leave out a side to go to the end: nums[:2] is the first two, nums[2:] everything from index 2.

nums = [10, 20, 30, 40, 50]
print(nums[1:3])
nums.append(60)
print(len(nums), 30 in nums)
Prints
[20, 30]
6 True

A for loop goes through a list item by item, which is how you total it or find the biggest. (Python also has sum(), max() and min() built in.)

Practice

What does this print?

days = ["Mon", "Tue", "Wed", "Thu"]
print(days[2])
More info

Quick reference

[a, b, c]A list. Indexes start at 0.
xs[i] / xs[-1]The item at index i / the last item.
xs[a:b]A slice: index a up to (not including) b.
len(xs)How many items.
xs.append(x)Adds x at the end.
x in xsTrue if x is in the list.

The other computer science courses