>>> Python for Beginners Chapter 08 of 10

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']

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