# Loop Techniques

> Python provides several advanced techniques to make loops more powerful and concise. Mastering these techniques is what separates beginner Python code...

Canonical: https://www.internhack.in/learn/python/control-flow/loop-techniques
Last updated: 2026-11-28

Difficulty: Beginner

Python provides several advanced techniques to make loops more powerful and concise. Mastering these techniques is what separates beginner Python code from professional-grade code.

The \`zip()\` function takes two or more iterables and combines them element-wise into tuples. It stops at the shortest iterable by default. This is invaluable when you need to iterate over multiple sequences in parallel without using index-based access.

List comprehensions provide a compact syntax for creating new lists by transforming and filtering elements from an existing iterable. The syntax is \`\[expression for item in iterable if condition\]\`. They are faster than equivalent for loops because they are optimized at the C level in CPython.

Python has a unique feature: an \`else\` clause on loops. The else block after a for or while loop executes only if the loop completed normally (without hitting a break). This is useful for search patterns where you want to take action when a target is not found.

These techniques are heavily tested in interviews because they demonstrate a deep understanding of Python's iteration protocol and the ability to write clean, idiomatic code.

## Code examples

### zip() -- parallel iteration

```
names = ["Alice", "Bob", "Carol"]
scores = [92, 85, 78]
grades = ["A", "B", "C+"]

for name, score, grade in zip(names, scores, grades):
    print(f"{name}: {score} ({grade})")
```

zip() combines three lists element by element. Each iteration unpacks one tuple of (name, score, grade). No index variable needed.

### List comprehension basics

```
# Transform: square each number
numbers = [1, 2, 3, 4, 5]
squares = [x2 for x in numbers]
print(f"Squares: {squares}")

# Filter: only even numbers
evens = [x for x in numbers if x % 2 == 0]
print(f"Evens: {evens}")

# Transform + Filter: square only odd numbers
odd_squares = [x2 for x in numbers if x % 2 != 0]
print(f"Odd squares: {odd_squares}")
```

List comprehensions combine mapping and filtering in one line. The if clause is optional and filters which elements are included.

### else clause on a for loop

```
def find_prime_factor(n):
    for i in range(2, n):
        if n % i == 0:
            print(f"{n} is divisible by {i}")
            break
    else:
        print(f"{n} is prime")

find_prime_factor(7)
find_prime_factor(12)
find_prime_factor(13)
```

The else block runs only when the loop finishes without break. If break is triggered (a factor is found), the else block is skipped. This is a clean pattern for search operations.

### zip() to build a dictionary

```
keys = ["name", "age", "city"]
values = ["Alice", 30, "Pune"]

person = dict(zip(keys, values))
print(person)

# Unzipping with zip(*...)
pairs = [(1, "a"), (2, "b"), (3, "c")]
nums, letters = zip(*pairs)
print(f"Numbers: {nums}")
print(f"Letters: {letters}")
```

zip() combined with dict() is a clean way to build dictionaries from parallel lists. The zip(\*iterable) pattern transposes rows and columns.

## Key points

- zip() stops at the shortest iterable. Use itertools.zip_longest() if you need to handle unequal lengths with a fill value.
- List comprehensions should remain readable. If the logic requires multiple lines or nested conditions, use a regular for loop instead.
- The for/else pattern is uncommon in other languages. The else runs when there is no break, which makes it ideal for 'item not found' scenarios.
- Dictionary comprehensions ({k: v for ...}) and set comprehensions ({x for ...}) follow the same syntax as list comprehensions.

## Interview tips

- Be ready to convert a for loop into a list comprehension and explain the trade-offs in readability vs. conciseness.
- The for/else pattern is a popular interview question. Explain it as: else runs when the loop terminates normally, without break.
- Know how to use zip() to transpose a matrix: list(zip(\*matrix)). This one-liner is frequently asked in coding interviews.
- Understand that list comprehensions are faster than equivalent for loops due to internal optimization, but readability always comes first.

## Concepts covered

zip(), list comprehension, else clause on loops, itertools basics, Pythonic iteration

Previous: [Nested Loops & Patterns](https://www.internhack.in/learn/python/control-flow/nested-loops-patterns) · [All of Control Flow](https://www.internhack.in/learn/python/control-flow)

## More Control Flow lessons

- [For Loops](https://www.internhack.in/learn/python/control-flow/for-loops)
- [While Loops](https://www.internhack.in/learn/python/control-flow/while-loops)

## Related

- [Learn](https://www.internhack.in/learn)
- [Python](https://www.internhack.in/learn/python)
- [Control Flow](https://www.internhack.in/learn/python/control-flow)
