Python Lists
Store many values together, in order
Big Idea: A list lets you keep many values in one variable, kept in order. Instead of
fruit1, fruit2, fruit3, you keep them all together in one tidy box called a list.
By the end you will be able to:
- create a list with square brackets
[ ], - read one item using its index,
- take a slice (a piece) of a list,
- add items with
append()and remove them withpop(), - go through every item with a
forloop.
1. What is a list?
A list is an ordered collection of values. You write it with square brackets and separate the items with commas.
fruits = ["apple", "banana", "cherry"]
print(fruits)
Output:
['apple', 'banana', 'cherry']
A list can hold text, numbers, or a mix. It even remembers the order you put things in.
numbers = [10, 20, 30, 40]
mixed = ["Ana", 12, True]
empty = []
print(numbers)
print(mixed)
print(empty)
Output:
[10, 20, 30, 40]
['Ana', 12, True]
[]
Analogy: A list is like a shopping list on paper: one line has many items, written in the order you thought of them.
2. Index: reading one item
Each item has a position number called an index. In Python, counting starts at 0 — the first item is index 0, the second is 1, and so on.
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[1])
print(fruits[2])
Output:
apple
banana
cherry
You can also count from the end using negative indexes. -1 is the last item, -2 is the one before it.
fruits = ["apple", "banana", "cherry"]
print(fruits[-1])
print(fruits[-2])
Output:
cherry
banana
A list with 3 items has indexes
0, 1, 2. Asking for fruits[3] is too far and causes an IndexError.