Python Arena
Step 1 of 6

Lists and indexes

Think of a program that keeps a week of temperatures. With what you know now, it would need seven variables, monday to sunday, and a program that reads values until the user stops couldn't work at all, because it can't make up new variable names as it runs. A list solves both problems: it keeps any number of values under one name. You write it in square brackets, with commas between the values:

temperatures = [18, 21, 17, 25]  # a list of four numbers
names = ["Ada", "Linus", "Grace"]
empty = []
print(temperatures)
print(names)
print(empty)
Output
[18, 21, 17, 25]
['Ada', 'Linus', 'Grace']
[]

The values in a list are its items (or elements). [] is an empty list, with no items yet. When you print a list, Python shows it the way you would write it in code, so strings in a list are shown with quotes, as in the interpreter.

Indexes

Each item has an index, its place in the list. As with the characters of a string, the first index is 0, and -1 is the last item:

temperatures = [18, 21, 17, 25]
print(temperatures[0])
print(temperatures[2])
print(temperatures[-1])
print("Change from first to last:", temperatures[-1] - temperatures[0])
Output
18
17
25
Change from first to last: 7

The function len gives the number of items, so the last index is len(temperatures) - 1. An index past the end stops the program:

temperatures = [18, 21, 17, 25]
print(len(temperatures))
print(temperatures[4])
Output
4
Python stops with
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(temperatures[4])
          ~~~~~~~~~~~~^^^
IndexError: list index out of range

The list has 4 items, at indexes 0 to 3. Index 4 would be a fifth item, which doesn't exist.

Changing an item

Unlike a string, a list can be changed after it's made. Give an item a new value as you would give a variable one:

temperatures = [18, 21, 17, 25]
temperatures[2] = 19
temperatures[0] = temperatures[0] + 1
print(temperatures)
Output
[19, 21, 19, 25]

The other items stay as they were. An index in square brackets on the left of = says which item gets the new value.

Your task

Challenge 1 of 3

Fill in the blanks so the program prints the number of planets in the list, the first planet, and then the list with Earth renamed to Terra:

Planets: 4
Closest to the sun: Mercury
['Mercury', 'Venus', 'Terra', 'Mars']

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

A house has the rooms in the list rooms, numbered from 1. Write a program that asks for a room number and prints that room's name. A number with no room prints No such room:

Room number: 2
Room 2 is the kitchen