Python
foreach
loop
programming
iteration

Python foreach equivalent

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python has no dedicated foreach keyword, but for ... in ... provides the same behavior in a more general form. It works with any iterable, including lists, tuples, dictionaries, strings, generators, and custom iterator types. Writing idiomatic loops in Python means leaning on iteration protocols instead of manual index management.

The Python Equivalent of Foreach

Basic foreach-style loop:

python
names = ["Ada", "Grace", "Linus"]
for name in names:
    print(name)

This directly iterates values, which is often clearer than index-driven loops.

Loop With Index Using enumerate

When index is required, use enumerate.

python
names = ["Ada", "Grace", "Linus"]
for idx, name in enumerate(names):
    print(idx, name)

Start index at one when needed:

python
for idx, name in enumerate(names, start=1):
    print(idx, name)

Iterating Dictionaries

Dictionary iteration can target keys, values, or both.

python
1user = {"id": 7, "name": "Ada", "role": "admin"}
2
3for key in user:
4    print(key)
5
6for value in user.values():
7    print(value)
8
9for key, value in user.items():
10    print(key, value)

items() is the closest to foreach over key-value pairs.

Iterating Files and Streams

Foreach-style loops are ideal for streaming large files.

python
1with open("events.log", "r", encoding="utf-8") as f:
2    for line in f:
3        process_line = line.strip()
4        if process_line:
5            print(process_line)

This processes one line at a time and avoids loading full file into memory.

Iterating With Generators

Generators are lazy iterables and fit naturally into foreach loops.

python
1def squares(n):
2    for i in range(n):
3        yield i * i
4
5for value in squares(5):
6    print(value)

Lazy iteration reduces memory usage for large sequences.

Foreach Versus Comprehensions

For data transformation, comprehensions are often more concise.

python
nums = [1, 2, 3, 4]
squares = [n * n for n in nums]

Use loops when side effects or multi-step logic are involved.

Common Control-Flow Patterns

Python loops support break, continue, and else.

python
1for n in [2, 4, 6, 7, 8]:
2    if n % 2 != 0:
3        print("found odd", n)
4        break
5else:
6    print("all even")

The else branch runs only if loop is not terminated by break.

Performance Notes

Loop performance is usually sufficient for application logic. For numeric heavy workloads, NumPy vectorization often outperforms pure Python loops. Optimize only after profiling to avoid premature complexity.

Writing Reusable Iteration Utilities

When the same loop pattern appears repeatedly, wrap iteration logic in helper generators so business code remains focused on domain behavior. Reusable iteration utilities also improve testability by allowing small deterministic inputs that cover edge cases without repeating loop scaffolding in every function.

Iteration in Data Pipelines

In ETL and log-processing scripts, foreach-style loops often coordinate parsing, validation, and transformation in one pass. Keeping each step as a small function called inside the loop improves readability and supports targeted unit tests for edge cases such as malformed lines, missing fields, and duplicate records.

Common Pitfalls

  • Rewriting C-style index loops when direct iteration is clearer
  • Modifying a list while iterating over it, causing skipped elements
  • Forgetting items() and iterating dictionaries incorrectly
  • Using list comprehension for side effects, reducing readability
  • Ignoring generator options and loading large data eagerly

Python iteration becomes cleaner when you focus on iterables, not counters.

Summary

  • Python uses for ... in ... as foreach equivalent.
  • Use direct iteration for clarity and enumerate when index is needed.
  • Use items() for dictionary key-value iteration.
  • Prefer generators for large or streaming data.
  • Pick loop style based on readability and workload profile.

Course illustration
Course illustration

All Rights Reserved.