A list holds several values in order. It is written in square brackets:
fruits = ["apple", "banana", "cherry"]
Positions start at zero
Each item has a position, called its index. The first item is at index 0:
print(fruits[0]) # apple
print(fruits[2]) # cherry
print(fruits[-1]) # cherry: negative numbers count from the end
print(len(fruits)) # 3
Replace an item by assigning to its index: fruits[1] = "blueberry".
Changing a list
| Code | What it does |
|---|---|
fruits.append("kiwi") | adds an item to the end |
fruits.insert(0, "fig") | adds an item at a position |
fruits.remove("apple") | removes the first matching item |
fruits.pop() | removes the last item and returns it |
fruits.sort() | sorts the list in place |
"kiwi" in fruits | True if the item is in the list |
Looping over a list
This is where for shines. The loop variable takes each item in turn:
for fruit in fruits:
print(fruit)
Helpful functions
For lists of numbers, Python has sum(), min() and max() built in:
scores = [70, 85, 92]
print(sum(scores)) # 247
print(sum(scores) / len(scores)) # the average
Slices
fruits[0:2] gives a new list with the items from index 0 up to, but not including, index 2.
Your Task
- Add
"Saturn"to the end of theplanetslist with a method. - Change the first item from
"Mercury"to"Venus". - Use a
forloop to print every planet on its own line. - After the loop, print how many planets are in the list.
"Saturn"is added to the end withappend- The first item is now
"Venus" - A
forloop prints all four planets in order - The number of planets,
4, is printed last
Lesson complete!
Next Lesson: Functions