Refactoring with zip() and enumerate()#

Student template

Continue in the same file you used for Filling the template: versions/07_student_template.py.

Here is one way to solve Filling the template by iterating over indices:

# Implementation that iterates over indices

outputs = []

# outer loop iterates over the indices of separate advertisements
for i in range(len(ADDRESSES)):
    output_for_this_address = []
    outputs.append(output_for_this_address)

    # inner loop iterates over lines in the template
    for j in range(len(REACTION_TEMPLATE)):
        line = REACTION_TEMPLATE[j]

        # construct the correct value for [[NAME]]
        names_connected = ""
        for k in range(len(NAMES[i])):
            if k == 0:
                pass
            elif k < len(NAMES[i]) - 1:
                names_connected += ", "
            else:
                names_connected += " & "

            names_connected += NAMES[i][k]

        line = line.replace("[[NAME]]", names_connected)
        line = line.replace("[[ADDRESS]]", ADDRESSES[i])
        line = line.replace("[[PRICE]]", str(PRICES[i]))
        line = line.replace("[[YOUR NAME]]", "John Doe")

        output_for_this_address.append(line)

for lines in outputs:
    print()
    print("\n".join(lines))

For the remainder of this assignment, feel free to use your own code or the example supplied. Instructions were tailored to the example above, but are likely applicable to your own solution too.

Issues in the example above#

The code above is hard to read. It contains deeply nested for-loops that use three separate variables to iterate over indices. This makes it difficult to understand what variable to use to index a particular data structure. A good (bad) example of this is the outer for-loop iterating over the indices of ADDRESSES using variable i. Clearly, i can be used to index ADDRESSES. However, the fact that i can be used to index PRICES is left implied. The person writing this code could easily have misinterpreted the situation and used j instead. This is a very common and nefarious source of bugs that can stay undetected because it does not always raise an exception.

It would be much clearer if each iteration of the for-loop created fresh instances of price, address, and names that belong together. This would automatically document that they belong together, something previously hidden in the iteration over indices. However, features that require index as an input, like creating names_connected (see above), as well as features that require simultaneous iteration over multiple lists (ADDRESSES, NAMES, PRICES), complicate this.

This demo is going to teach you three easy to apply tricks that together can solve this issue for 99% of all for-loops you will ever encounter. They will make it a lot more fun and convenient to work with for-loops and make your code significantly more readable.

Tasks#

Task 1: Iterating over elements instead of indices#

Looping with "for fruit in fruits" is readable, while "for i in range(len(fruits))" with fruits[i] is painful.

As teased above, Python code becomes easier to read if you iterate directly over elements instead of indices. The reason for this is three-fold. Firstly, you turn a non-descript variable i into a properly named variable like fruit. Secondly, you reduce the amount of square brackets on screen. This is one fewer detail that your eyes can be distracted by. Finally, it makes your code closer to natural language. The statement for fruit in fridge: do this is a sentence that is understandable even to non-programmers.

(a) Refactor the iteration over lines in the REACTION_TEMPLATE to iterate over elements instead of indices.

Task 2: The enumerate() function pairs element with index#

The enumerate() function takes a Python list as argument and pairs each element of the list with its index. This lets you use element-wise iteration even if your code also requires information about the position of each element within the list.

When you need the step number, range(len(fruits)) makes it easy, but looping over the fruits directly seems to make it impossible.

Using enumerate() is an easy way to make your code more readable.

# without enumerate
for i in range(len(fruits)):
	print(f"Step {i}: Add one {fruits[i]}")

	
# using enumerate
	
# tuple unpacking into i and fruit
#    v
for i, fruit in enumerate(fruits):
	print(f"Step {i}: Add one {fruit}")

enumerate() outputs a list[1] containing tuples of (index, element).

enumerate(fruits) pairs each fruit with its index 0 to 4, so "for i, fruit in enumerate(fruits)" is easy and readable.

(a) Refactor the code to use enumerate() in the for-loop constructing names_connected. The index can help you tell whether to put a comma or an ampersand between individual names.

Task 3: The zip() function groups elements of different lists#

At this point, only one purely index-based iteration should be left in the code. The outer for-loop iterates over separate advertisements and groups elements of NAMES, ADDRESSES, and PRICES together if they have the same index. In order to turn this construction into element-wise iteration, you will make use of the zip() function.

Looping over range(len(fruits)) to print names[i] with fruits[i] never mentions the names list in the loop header.

Like the name implies, zip() zips together two or more lists into a single list[1] such that elements with the same index are paired together. To zip together lists, simply supply them to zip() as arguments separated by a comma.

zip(names, fruits) pairs each name with its fruit, so "for name, fruit in zip(names, fruits)" is finally readable.

Each group of elements of the same index is stored in a tuple. The order within that tuple reflects the order of arguments supplied to zip(). This makes it easy to access them with tuple unpacking.

numbers = [1, 2, 3, 4, 5]
names = ['banana', 'apple', 'orange', 'berry', 'apple']
fruits = ['🍌', '🍎', '🍊', '🍓', '🍎']

# index-based: only groups indices together by implication
for i in range(len(numbers)):
	print(f"{numbers[i]}: {names[i]} has icon {fruits[i]}")
	
# element-based with zip: groups elements together explicitly
for number, name, fruit in zip(numbers, names, fruits):
	print(f"{number}: {name} has icon {fruit}")

(a) Refactor the outer for-loop to use zip() to iterate over advertisements. Supply all relevant lists to zip() and unpack the output into appropriately named variables.

Task 4: Easy readability wins#

As a final touch, we will move calculations that only need to happen once per iteration out of the inner for-loop. This helps keep the for-loop small and readable.

(a) Move the name-construction loop out of the inner loop.