Skip to content

Lists: index, append, slice and in

BeginnerLesson 5 of 146 min

Keep things in order with Python lists: read items by position, add with append(), copy a part with a slice, and check what’s there with in and len().

A list keeps values in order, between square brackets:

packing = ["tent", "stove", "map"]
print(packing[0], packing[-1])  # tent map
print(len(packing))             # 3

Positions work exactly like a string's: from 0, and negative ones from the end. Slices work the same way too, and give you a new list:

packing = ["tent", "stove", "map", "torch"]
print(packing[1:3])  # ['stove', 'map']
print(packing[:2])   # ['tent', 'stove']

Lists can change

Unlike a string, a list can be changed in place:

packing = ["tent", "stove", "map"]
packing.append("torch")   # add to the end
packing.insert(0, "boots")  # add at a position
packing.remove("stove")   # take out the first "stove"
packing[1] = "big tent"   # replace an item
last = packing.pop()      # take the last item off, and get it back
print(packing, last)
['boots', 'big tent', 'map'] torch

append changes the list and gives back None, so write packing.append("torch") on its own, never packing = packing.append(...).

Is it there?

in asks whether a value is in the list, and gives True or False:

packing = ["tent", "stove", "map"]
print("map" in packing)        # True
print("compass" in packing)    # False
print("compass" not in packing)  # True

A list can hold anything, even a mix: [3, "three", 3.0, None]. Usually, though, one list holds one kind of thing.

Try it:Ask for packing[10]. The IndexError says the position is past the end; a slice like packing[1:10] just stops at the end instead.

More in the Python docs: lists in the tutorial and list methods.

Your turn

queue is a playlist. Add "Morning" to the end with append. Make first_two the first two songs with a slice, and has_rain whether "Rain" is in the queue, using in. Finally, print how many songs are in the queue now, with len().

Next →