Data Structures · Lists · lesson 1 of 10
Creating and indexing lists
about 10 minutes · free · runs in your browser
Step 1 of 2
A list of values
A list holds several values in order, written in square brackets:
colours = ["red", "green", "blue"]
mixed = [1, "two", 3.0, True]
empty = []
Python does not mind what you put in a list, though in practice keeping one type per list saves you trouble.
You reach a single item by its index, and indexes start at zero:
colours[0] # "red"
colours[2] # "blue"
Negative indexes count from the end, which saves the arithmetic:
colours[-1] # "blue" — the last one
colours[-2] # "green"
Asking for an index that does not exist raises IndexError. len(colours) gives you
the count, so the last valid index is always len(colours) - 1.
Your turn: pull the first, third and last planets out of the list.
You start from this, and edit it in the browser:
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter"]
# Set first, third and last.
Step 2 of 2
Changing a list
Lists are mutable — you can change them after creating them:
colours[0] = "crimson" # replace in place
colours.append("yellow") # add to the end
colours.insert(1, "amber") # add at a position
append is the workhorse. Note that it changes the list and returns None, so
colours = colours.append("x") is a classic mistake that throws your list away.
From here on the exercises are written as functions, the shape you met in Python Basics:
def name(parameter):, an indented body, and return to hand the answer back. You never
call it yourself — the tests do, with lists of their own — so items is whatever they
pass in, and return is how they see your result.
Your turn: write add_and_replace(items) that replaces the first item with
"first", appends "last", and returns the list.
You start from this, and edit it in the browser:
def add_and_replace(items):
# Replace the first item, append "last", return the list.
pass