Skip to content
FORGENO ADS GAMESUnlock all $8

Python Programming · Unit 3 of 8

Unit 3: Loops and lists

for loops and range, totals and new lists, list methods, changing a list versus copying it, tuples, unpacking, zip and enumerate, and the patterns behind searching and filtering.

Opens the first lesson of this unit in Python Programming. Every lesson is open from the start.

Lesson 1: for loops and range

Goal: Loop over sequences and ranges, accumulate totals and counts, and choose between for and while.

A for loop runs its block once for each item in a sequence, giving the item a name each time round. It ends by itself when the items run out, so there is no counter to forget. Use for when you know what you are looping over (a list, a string, a range of numbers) and while when you loop until something changes.

for name in ["Ana", "Ben", "Cy"]:
    print("Hello,", name)

for ch in "hey":
    print(ch.upper())

range() produces a sequence of whole numbers for counting loops. range(5) gives 0, 1, 2, 3 and 4: five numbers, starting at 0 and stopping before 5. range(2, 6) gives 2, 3, 4 and 5. A third argument is the step: range(0, 20, 5) gives 0, 5, 10 and 15, and range(5, 0, -1) counts down 5, 4, 3, 2, 1. Like slices, the stop value is never included, so range(len(items)) gives exactly the valid indexes of a list.

The accumulator pattern is the workhorse of data processing: create a variable before the loop (a total of 0, a count of 0, an empty list), update it inside the loop, and use it after the loop. If you need each item's position as well, enumerate() gives you pairs of (index, item): for i, name in enumerate(names, start=1): numbers the names from 1.

prices = [4.5, 12.0, 3.25, 20.0]
total = 0
expensive = 0
for i, price in enumerate(prices, start=1):
    total += price
    if price > 10:
        expensive += 1
    print(f"{i}. {price:.2f}")
print(f"Total {total:.2f}, {expensive} over 10")

Worked example: a total, a count and a numbered list in one pass

  1. Before the loop: total and expensive start at 0.
  2. Each round, enumerate hands over the position (from 1) and the price.
  3. The total grows by each price; the count grows only when the price is over 10.
  4. After the loop, the totals are complete and are printed once.

Output: four numbered prices, then Total 39.75, 2 over 10. One loop computed three things.

Hands-on lab in the room: Python playground.

Hands-on lab in the room: Unit 3 coding exercises. Graded exercise: build a list in a loop, then total and average it.

for loop
A loop that runs its block once for each item in a sequence.
range()
A sequence of whole numbers, range(start, stop, step), that stops before stop.
Accumulator
A variable created before a loop and updated inside it, such as a running total.
enumerate()
Gives (index, item) pairs while looping, optionally starting from a number other than 0.
Iterate
To go through the items of a sequence one at a time.

Remember: for walks through items and stops on its own. range(n) is 0 to n-1. Set up accumulators before the loop.

Lesson 2: Lists

Goal: Create and change lists with their methods, and tell changing a list apart from copying it.

A list is an ordered collection of values in square brackets: basket = ["pen", "ink", "pad"]. Lists can hold any types, even other lists, and can grow and shrink. They are indexed and sliced exactly like strings, but unlike strings they are mutable: you can change them in place, so basket[0] = "pencil" works.

Working with lists
CodeEffect
basket.append("tape")adds one item to the end
basket.insert(0, "clip")inserts at a position
basket.extend(["a", "b"])adds every item of another list
basket.pop() / basket.pop(0)removes and returns the last (or given) item
basket.remove("ink")removes the first matching item (ValueError if absent)
"ink" in basketTrue if the item is present
basket.index("pad")position of the first match
len(basket), sum(nums), min(nums), max(nums)size, total, smallest, largest

Sorting comes in two flavours. nums.sort() sorts the list in place and returns None. sorted(nums) returns a new sorted list and leaves the original untouched. A classic bug is nums = nums.sort(), which replaces your list with None. Both accept reverse=True, and both can sort by a rule, such as sorted(words, key=len), which you will use a lot in Unit 7.

Assignment does not copy. b = a makes b a second name for the same list, so a change made through either name shows up in both. This sharing is called aliasing. When you need an independent copy, write b = a.copy(), b = list(a) or b = a[:]. Functions receive the same list object too, which is why Unit 5 teaches functions to return new lists rather than quietly changing the one they were given.

a = [1, 2, 3]
b = a          # same list, two names
c = a.copy()   # a new, separate list
b.append(4)
c.append(99)
print(a)   # [1, 2, 3, 4]
print(b)   # [1, 2, 3, 4]
print(c)   # [1, 2, 3, 99]

Worked example: aliasing versus copying

  1. b = a: no new list is made. a and b both point at the one list.
  2. c = a.copy(): a brand-new list with the same items.
  3. b.append(4) changes the shared list, so printing a shows the 4 as well.
  4. c.append(99) changes only the copy.

Step through it in the tracer below: watching both names show the same change makes aliasing click.

Hands-on lab in the room: Predict-the-output tracer. Predict the output, then step through it.

List
An ordered, changeable collection of values in square brackets.
Mutable
Able to be changed in place after it is created. Lists, dictionaries and sets are mutable.
Aliasing
Two or more names referring to the same object, so a change through one is seen through all.
sorted() vs sort()
sorted() returns a new sorted list; list.sort() sorts in place and returns None.

Remember: Lists change in place. b = a shares one list; a.copy() makes a new one. sort() returns None; sorted() returns a list.

Lesson 3: Tuples, unpacking and zip

Goal: Use tuples for fixed groups of values, unpack them into names, and walk two lists together with zip.

A tuple is like a list that cannot change: an ordered group of values in parentheses, such as point = (3, 4) or row = ("Ana", 82, True). Use a tuple for a fixed bundle whose parts have set meanings, like a coordinate, an RGB colour or one row of data. Because tuples are immutable, they are safe to pass around and can be used as dictionary keys, which lists cannot.

Unpacking assigns the parts of a sequence to several names in one go: x, y = point sets x to 3 and y to 4. The number of names must match the number of items, or Python raises a ValueError. Unpacking gives you the neatest swap in any language, a, b = b, a, and it is how a function returns several values (Unit 5): low, high = min_max(nums). A starred name collects the rest: first, *rest = [1, 2, 3, 4] gives first = 1 and rest = [2, 3, 4].

point = (3, 4)
x, y = point
print(x, y)

a, b = 1, 2
a, b = b, a            # swap
print(a, b)

first, *rest = [10, 20, 30, 40]
print(first, rest)

zip() walks through two or more sequences side by side, giving a tuple of matching items each time. It stops at the end of the shortest sequence. Combined with unpacking in the for line, it is the clean way to handle data that arrives as parallel lists, such as names in one list and scores in another.

names = ["Ana", "Ben", "Cy"]
scores = [82, 91, 77]
for name, score in zip(names, scores):
    print(f"{name:<4} {score}")
best = max(zip(scores, names))
print("Best:", best)

Worked example: pairing names with scores

  1. zip(names, scores) produces ("Ana", 82), ("Ben", 91) and ("Cy", 77).
  2. The for line unpacks each pair into name and score.
  3. zip(scores, names) puts the score first, so max compares tuples by their first item.
  4. Tuples compare item by item, so the largest is (91, "Ben").

Output: three aligned lines, then Best: (91, 'Ben').

Hands-on lab in the room: Python playground.

Hands-on lab in the room: Unit 3 coding exercises. Graded exercise: zip, unpacking and tracking the best so far.

Tuple
An ordered, unchangeable group of values, written in parentheses: (3, 4).
Unpacking
Assigning the items of a sequence to several names at once: x, y = point.
zip()
Walks several sequences side by side, giving a tuple of matching items each time.
Starred assignment
A name with * that collects the remaining items into a list: first, *rest = items.

Remember: Tuples are fixed bundles. x, y = pair unpacks; a, b = b, a swaps. zip pairs up parallel lists and stops at the shortest.

Lesson 4: Loop patterns: search, filter and nest

Goal: Write the standard loop patterns: find the first match, filter into a new list, track the best so far, and nest loops.

Most loops in real code are one of a handful of patterns. Recognising them makes code faster to write and easier to read.

Six loop patterns
PatternShapeExample
Accumulatestart a total, add each itemtotal revenue
Countstart at 0, add 1 when a condition holdsorders over 100
Filterstart an empty list, append matching itemscustomers in Lakeside
Transformstart an empty list, append a changed itemprices with tax
Searchstop at the first match with breakfirst overdue invoice
Best so farkeep the best item, replace it when beatenhighest score

Search with break: loop until you find what you want, then stop. Python has a neat extra: a for loop can have an else block, which runs only if the loop finished without hitting break. That is exactly the "not found" case, so you do not need a separate found flag.

invoices = [("A1", 12), ("A2", 45), ("A3", 3), ("A4", 60)]   # (id, days open)
for inv_id, days in invoices:
    if days > 30:
        print("First overdue:", inv_id)
        break
else:
    print("Nothing overdue")

Worked example: the first overdue invoice

  1. A1 has been open 12 days: not overdue, keep looking.
  2. A2 has been open 45 days: overdue, so print it and break.
  3. Because the loop ended with break, the else block is skipped.
  4. If no invoice were over 30 days, the loop would finish normally and else would print "Nothing overdue".

Output: First overdue: A2. A4 is never even looked at: stopping early saves work on big lists.

Loops can be nested: a loop inside a loop runs the inner loop completely for every round of the outer one. This handles grids (rows, then columns), comparing every pair of items, or a times table. Count the work: an outer loop of 100 items with an inner loop of 100 runs the inner block 10,000 times. That multiplication is the root of the Big-O ideas in Unit 7.

Hands-on lab in the room: Python playground.

Hands-on lab in the room: Unit 3 coding exercises. Graded exercise: search with break and for...else.

Linear search
Checking items one by one, in order, until a match is found or the items run out.
Filter
Building a new list that keeps only the items that match a condition.
for...else
An else block after a loop that runs only when the loop ended without break.
Nested loop
A loop inside another loop; the inner loop runs fully for every round of the outer one.

Remember: Name the pattern before you write the loop: accumulate, count, filter, transform, search or best so far.

Practise it in Python Programming

Each lesson ends with three questions that check you can use the idea, not just recognise it. Wrong answers explain why and come back in Review. The unit ends with a 7-question quiz; pass it with 80% or more to master the unit. Hands-on lab: Predict-the-output tracer and Unit 3 coding exercises.

Every lesson is free: no ads, no lives and no paywall.