Functions and Lists
≈ 30 minFunctions: naming a block of steps
When you find yourself writing the same steps again and again, wrap them in a function. A function has a name, can take inputs (parameters) inside the brackets, and can return a result.
def area(length, width):
return length * width
print(area(5, 3)) # 15
print(area(10, 2)) # 20def starts the definition. You call the function by writing its name with values in the brackets. return hands a value back to whoever called it.
Runs in your browser. Charts (matplotlib) are not supported — use print-based output.
Lists: many values in one box
A single variable holds one value. A list holds many, in order, inside square brackets:
temps = [21, 24, 19, 28, 23]
print(temps[0]) # 21 (first item, index 0)
print(len(temps)) # 5 (how many items)
temps.append(30) # add 30 on the endEach item has an index (position) starting at 0. Useful tools: len(list) counts items, list.append(x) adds one, sum(list) totals numbers.
Looping over a list
A for loop can walk through every item in a list, which is where functions and lists become powerful together:
temps = [21, 24, 19, 28, 23]
hot_days = 0
for t in temps:
if t >= 25:
hot_days = hot_days + 1
print(hot_days) # 1The loop variable t becomes each temperature in turn, and the if counts the hot ones.
Runs in your browser. Charts (matplotlib) are not supported — use print-based output.
Given this list:
rivers = ["Orange", "Vaal", "Limpopo", "Tugela"]
print(rivers[1])What is printed?
A function returns the average of a list:
def average(values):
return sum(values) / len(values)
marks = [60, 80, 70, 90]
print(average(marks))What number is printed?
Which Python list method adds a new item to the end of a list, as in chores.____("sweep")? (One word, no brackets.)

