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)) # 3Each 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]) # cherryNegative indexes count from the end. -1 is the last item:
print(fruits[-1]) # cherry
print(fruits[-2]) # bananaLists 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.
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).
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.