All lessons

Lists & loops · step 12 of 22

Lists: many values in one place

9 minStore, read, add and reorder a collection of values.

A list holds many values in order

colors = ["red", "green", "blue"]
numbers = [3, 1, 4, 1, 5]
mixed = ["Ada", 36, True]

Positions start at 0, and -1 means the last item.

print(colors[0])      # red
print(colors[-1])     # blue
print(len(colors))    # 3

Lists can change

Unlike strings, a list is mutable — you can add, remove and reorder items in place.

numbers.append(9)      # add to the end
numbers.remove(1)      # remove the first 1
numbers.sort()         # smallest to largest, in place
print(numbers)

Slicing works exactly like strings: colors[0:2] is ["red", "green"], and "a" in colors asks whether a value is in the list.

Reading the last item safely

Ask for an index that does not exist and Python raises IndexError — a list of 3 items has indexes 0, 1 and 2, and nothing else.

Remember this

  • Lists keep values in order and can change
  • Index from 0; -1 means the last item
  • append, remove and sort change the list itself

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. colors = ['red', 'green', 'blue'] — what is colors[-1]?

  2. 2. What does len([4, 8, 15]) give?

  3. 3. Which line adds 9 to the end of a list called numbers?

Answer all three to check them.

Now write it yourself

0/3 passed
1

Practice 1

The list `colors` is ready. Print the last colour using a negative index, then print how many colours there are.

practice_1.py

Given for you

colors = ["red", "green", "blue"]
2

Practice 2

The list `numbers` is ready. Add 3 to the end, sort the list, then print it.

practice_2.py

Given for you

numbers = [5, 1, 9]
3

Practice 3

Build your own list called `skills` with three things you want to learn. Print how many skills are on your list, then print the first one.

practice_3.py

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.