Lesson 2 of 3
Repeat code for every item in a collection with for, count with range(), build running totals, and loop over dictionaries.
About 30 minutes
range() to repeat code a set number of timesitems() and number items with enumerate()Suppose you need to convert 200 temperatures to kelvin. Writing 200 print() lines is impractical, and the program would break as soon as the data changed. A loop runs the same block of code repeatedly. A for loop runs its block once for each item in a collection.
The line for element in elements: reads naturally: for each element in the list of elements, do the following. Each time round the loop, the loop variable (element) holds the next item. The indented block is the body of the loop. When the items run out, Python continues after the loop.
elements = ["Fe", "Ni", "Cr"]for element in elements: print("Element:", element)print("Done")You can choose any name for the loop variable. A good habit is to use the singular of the collection's name: for sample in samples, for temperature in temperatures. A for loop works with any collection, including strings (one character at a time) and tuples.
Convert a heat-treatment schedule from °C to K.
schedule_c = [20, 450, 850, 1050]for temperature in schedule_c: kelvin = temperature + 273.15 print(f"{temperature:>5} °C = {kelvin:.2f} K")Sometimes you want to repeat something a number of times rather than loop over existing data. range() produces a sequence of whole numbers for a for loop to step through. Like slicing, the stop value is never included.
| Call | Numbers produced |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(0, 1000, 250) | 0, 250, 500, 750 |
range(10, 0, -3) | 10, 7, 4, 1 |
# Temperatures from 300 K to 600 K in steps of 100 Kfor temperature in range(300, 601, 100): print(temperature, "K")A very common pattern is the accumulator: create a variable before the loop, then update it each time round. This is how you add up values, count items that meet a condition, or find a maximum yourself.
masses = [12.5, 8.3, 15.2, 9.0] # gtotal = 0for mass in masses: total += massprint(f"Total mass: {total} g")print(f"Mean mass: {total / len(masses):.2f} g")Combining a loop with if lets you act only on certain items. Here the loop counts how many readings fall outside a tolerance and builds a new list of the ones that pass.
readings = [8.94, 8.97, 9.31, 8.95, 8.60, 8.96] # g/cm³target, tolerance = 8.96, 0.05accepted = []rejected_count = 0for reading in readings: if abs(reading - target) <= tolerance: accepted.append(reading) else: rejected_count += 1print("Accepted:", accepted)print("Rejected:", rejected_count)A for loop over a dictionary gives its keys. To get each key together with its value, loop over items() and unpack each pair into two variables, just as you unpacked tuples.
densities = {"aluminium": 2.70, "titanium": 4.51, "iron": 7.87, "copper": 8.96}for metal, density in densities.items(): print(f"{metal:<10} {density:.2f} g/cm³")The same unpacking works for any list of tuples, which is a common way to store small tables of records.
atomic_masses = {"H": 1.008, "C": 12.011, "O": 15.999}ethanol = [("C", 2), ("H", 6), ("O", 1)] # (element, count)molar_mass = 0for element, count in ethanol: molar_mass += atomic_masses[element] * countprint(f"Molar mass of ethanol: {molar_mass:.2f} g/mol")When you need each item's position as well as its value, wrap the collection in enumerate(). It produces (index, item) pairs. Pass start=1 to number from 1 for display.
samples = ["Cu-01", "Cu-02", "Cu-03"]for number, sample in enumerate(samples, start=1): print(f"{number}. {sample}")List comprehensions
kelvin = [t + 273.15 for t in celsius]. This is a list comprehension. It does the same as creating an empty list and appending inside a for loop. Use whichever you find clearer.Choose an answer and press Check answer. You can retry as often as you like.