Pulsars
0 %
Log inSign up

Lists

Creating and manipulating a list

Creating and manipulating a list

A list is a structure that lets you store several values, in a specific order, under a single variable name. In Python, you create a list with square brackets, separating the elements with commas:

notes = [12, 15, 8, 17]
fruits = ["apple", "banana", "kiwi"]

Each element of a list has an index (its position), which always starts at 0, not 1:

notes = [12, 15, 8, 17]
print(notes[0])   # (displays 12, the first element)
print(notes[1])   # (displays 15, the second element)
print(notes[3])   # (displays 17, the last element)

Common mistake: forgetting that indexing starts at 0. The first element of a 4-element list has index 0, and the last has index 3, not 4. If you try to access an index that doesn't exist (for example notes[4] here), Python displays an IndexError.

To find out the number of elements in a list, use the len function:

print(len(notes))   # (displays 4)

You can also modify an existing element by assigning a new value to its index:

notes[0] = 20
print(notes)   # (displays [20, 15, 8, 17])

Lists are mutable: unlike a string, you can change its content after it's created, without having to recreate the whole list.