Codiqo

Learn Python · lesson 25 of 60 · about 6 minutes

Creating and Indexing Lists

Plan by the day: keep the days of the week in one list, and read a day by its position.

What you'll learn

  • Write list literals
  • Read items by index
  • Change an item in place

Planning by day

The assistant can now plan by the day. The seven days live in one list, days, in order, so day 3 is days[2]: people count from 1, but lists count from 0. Before using a typed number as an index, the planner checks that it's a day at all, and days[-1] always means the last one, Sunday.

One variable, many values

A list holds several values in order, inside square brackets and separated by commas. Lists can hold any type, and len() tells you how many items there are.

Indexing works exactly like strings: the first item is [0] and the last is [-1].

A list of scores

scores = [12, 40, 7, 25]
print(scores)
print(len(scores))
print(scores[0], scores[-1])

Output

[12, 40, 7, 25]
4
12 25

Lists can change

Unlike strings, you can change an item in a list by assigning to its index. Lists are *mutable*; strings are not.

Changing an item

pets = ["cat", "dog", "fish"]
pets[1] = "penguin"
print(pets)

Output

['cat', 'penguin', 'fish']

Tip

Asking for an index that doesn't exist, like pets[3] in a 3-item list, causes an IndexError. The last valid index is len(list) - 1.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.