Syllabus Lesson 28 of 239 · Data Structures
Data Structures

Lists: Create, Index, Mutate

A list holds many values in order, inside square brackets. Think of it as a row of labelled boxes.

fruits = ["apple", "banana", "cherry"]
print(fruits)        # ['apple', 'banana', 'cherry']
print(len(fruits))   # 3

Each item has a position called an index. Counting starts at 0, not 1. So the first item is index 0:

print(fruits[0])   # apple
print(fruits[1])   # banana
print(fruits[2])   # cherry

Negative indexes count from the end. -1 is the last item:

print(fruits[-1])  # cherry
print(fruits[-2])  # banana

Lists are mutable, meaning you can change them after creating them. Assign to an index to replace one item:

fruits[1] = "blueberry"
print(fruits)      # ['apple', 'blueberry', 'cherry']

Reading an index that does not exist raises an IndexError, so keep indexes between 0 and len(list) - 1.

Your turn

Start from the list colors = ["red", "green", "blue"]. Change the last item to "purple", then print the first item and the last item (each on its own line).

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output