List Basics

A list holds several values in order. You create a list with square brackets [ ]. Each value has a position number, called an index. The first index is 0, not 1.

colors = ["red", "blue", "green"]

print(colors[0])
print(colors[-1])
print(len(colors))

colors[1] = "gold"
print(colors)

Output:

red
green
3
['red', 'gold', 'green']

Positive indexes count from the start. Negative indexes count from the end, so -1 means the last value. len gives the number of values in the list.

Lists are mutable. This means you can change them after you create them. The line colors[1] = "gold" puts "gold" at index 1, in place of "blue". If you ask for a position that does not exist, such as colors[5], the program stops with an IndexError.

A list can hold values of different types, such as numbers and text together. But a list of similar values is usually easier to work with.

In the exercise, print the list's length and the values at some positions.