Guide Python Beginner

10.9 Traversing and List Comprehensions

Four idiomatic ways to visit every element of a list -- for, while, enumerate(), and zip() -- plus list comprehensions as the compact, expression-based alternative to a manual loop with append().

3 min read

Traversing

for

The standard, most Pythonic way to iterate — no manual index bookkeeping needed.

>>> for x in [1, 2, 3]:
...     print(x, end=" ")
1 2 3

while

Manual index-based iteration — occasionally needed when the index itself must be controlled directly (skipping, jumping), but for is preferred otherwise.

i = 0
lst = [10, 20, 30]
while i < len(lst):
    print(lst[i], end=" ")
    i += 1
# Output: 10 20 30

enumerate()

Yields (index, value) pairs together — the idiomatic way to get both the position and the value without managing a counter manually.

>>> for i, v in enumerate(["a", "b", "c"]):
...     print(i, v)
0 a
1 b
2 c

zip()

Iterates several lists together in parallel, pairing up corresponding elements — stops at the shortest input.

>>> for a, b in zip([1, 2, 3], ["x", "y", "z"]):
...     print(a, b)
1 x
2 y
3 z

List Comprehensions

A compact, single-line syntax for building a new list by transforming and/or filtering an existing iterable: [expression for item in iterable if condition]. More concise, and often faster, than the equivalent explicit for loop with .append() calls.

Basic

>>> squares = [x**2 for x in range(5)]
>>> squares
[0, 1, 4, 9, 16]

Conditional

Adding if filters which items make it into the result.

>>> evens = [x for x in range(10) if x % 2 == 0]
>>> evens
[0, 2, 4, 6, 8]

Nested

A comprehension inside another comprehension — commonly used to build a matrix; see 10.10 Nested Lists and Matrices.

>>> [[x * y for y in range(3)] for x in range(3)]
[[0, 0, 0], [0, 1, 2], [0, 2, 4]]

Multiple Loops

A single comprehension can iterate more than one for clause, producing every combination — equivalent to nested for loops flattened into one expression.

>>> [(x, y) for x in range(2) for y in range(2)]
[(0, 0), (0, 1), (1, 0), (1, 1)]

Quick Interview Answer

for is the default way to traverse a list; while is reserved for cases needing direct index control. enumerate() gives index-value pairs without a manual counter, and zip() walks multiple lists in parallel, stopping at the shortest. List comprehensions compress the extremely common ’loop + filter + transform + append’ pattern into one expression — [expr for item in iterable if condition] — and are generally both more readable and faster than the equivalent explicit loop, right up until the logic gets complex enough that the comprehension itself becomes hard to read, at which point a full loop is the better choice.”

Common Mistakes

  • Reaching for a while loop with manual indexing when a plain for loop would do the same job more simply and without off-by-one risk.
  • Forgetting zip() silently stops at the shortest input instead of raising an error — mismatched-length inputs can hide a bug rather than surface one.
  • Writing a deeply nested comprehension with multiple conditions that’s harder to read than the equivalent explicit loop — comprehensions are a readability tool first, not a rule to apply unconditionally.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form