Lists: ordered collections

Lists & Tuples, lesson 1 of 6

📋 Lists & Tuples, lesson 1 of 6

Lists: ordered collections

Keep many values in one variable and reach them by position.

8 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

A list stores many values, in order, in a single variable. Write the items inside square brackets, separated by commas:

scores = [120, 95, 87]
empty = []

Each item has an index (its position). Like string characters, indexes start at 0, and negative indexes count from the end: -1 is the last item.

Example

Your playlist

Add your favourite song to the list. Does playlist[-1] still find the last one?

Lists are mutable: you can change an item by assigning to its index. The in operator tells you whether a value is in the list.

Example

Update the leaderboard

Try scores[-1] = 200. Which score changes?

Quiz

What does this print?

Example

Index out of range

Change colors[3] to colors[2] to fix it.

Exercise

Fix the menu

Today's menu changed:

  1. Replace "pasta" with "pizza" (assign to its index).
  2. Set count to the number of dishes with len.
  3. Set dessert to the last dish, using a negative index.
Quiz

A list has 10 items. What is the index of its last item?