Chapter 08 ยท Collections
Lists
One variable holds one thing. But real life comes in groups: a class of students, a shopping cart, a week of sales. A list holds many things under one name.
Real-world analogy
A list is a shopping trolley. It holds many items in order, you can add or remove things, and each item has a position. One trolley (one variable) carries the whole shop.
Making a list
Square brackets, items separated by commas:
fruits = ["apple", "banana", "mango"]
print(fruits)
print(fruits[0])
print(fruits[2])
['apple', 'banana', 'mango']
apple
mango
Like strings, list positions start at 0, so fruits[0] is the first item.
Adding, changing and removing
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)
fruits[0] = "pear"
print(fruits)
fruits.remove("banana")
print(fruits)
['apple', 'banana', 'orange']
['pear', 'banana', 'orange']
['pear', 'orange']
.append(x)adds x to the end.list[i] = xreplaces the item at position i..remove(x)deletes the first matching item.len(list)tells you how many items there are.
Looping over a list โ the real power
This is where lists and loops combine beautifully:
prices = [1500, 400, 2800]
total = 0
for price in prices:
total = total + price
print(f"Total: K{total}")
Total: K4300
โ๏ธ Try it yourself
Make a list of five of your friends' names. Print how many there are with len(), then use
a for loop to print "Hello, [name]!" for each one.
Recap
- A list holds many ordered items:
["a", "b", "c"]. - Access by position (from 0); change, add (
.append) and remove (.remove). - Loop over a list with
for item in list:โ this is one of the most-used patterns in all of programming.