TutreNews Learn

Lists

Looping and list comprehensions

Goal: Loop with enumerate and zip and build new lists with comprehensions · 11 min

Looping over a list directly is the Python way:

for fruit in fruits:
    print(fruit)

When you also need the index, use enumerate; to walk through two lists in parallel, use zip:

for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
for name, age in zip(names, ages):
    print(name, age)

Never change the length of a list while looping over it; build a new list instead.

A list comprehension builds a new list in one line: [expression for item in iterable if condition].

squares = [n * n for n in range(1, 6)]            # [1, 4, 9, 16, 25]
evens   = [n for n in range(10) if n % 2 == 0]    # [0, 2, 4, 6, 8]
upper   = [w.upper() for w in ["a", "b"]]         # ['A', 'B']

Read it as: "the expression, for every item, optionally only if…". The condition filters; the expression transforms. A transformation with a choice puts the if/else before the for: ["even" if n % 2 == 0 else "odd" for n in range(3)].

Nested lists model tables: grid = [[1, 2], [3, 4]]; grid[1][0] is 3 (row 1, column 0). Useful helpers: sum(list), min(list), max(list), len(list).

Worked example: From loop to comprehension

  1. Loop version: create an empty list, loop, append n * 2 if n > 2.
  2. Comprehension: [n * 2 for n in nums if n > 2].
  3. Both give [6, 8, 10] for nums = [1, 2, 3, 4, 5].
nums = [1, 2, 3, 4, 5]
result = []
for n in nums:
    if n > 2:
        result.append(n * 2)
print(result)
print([n * 2 for n in nums if n > 2])

Output:

[6, 8, 10]
[6, 8, 10]