For Loop In Python — PBA Institute Tutorial
Chapter 05 · Python Programming Series
12 min read Beginner

Iteration With The For Loop

The Python for loop is arguably the most-used construct in real production code. It walks over any iterable — lists, strings, dictionaries, tuples, files, generators — with a clean, readable syntax. In this lesson you'll go beyond range() and learn every pattern professional Python developers use every day.

Overview

📜

Reads Anything

Iterate strings, lists, tuples, dicts, sets, files, generators with one syntax.

⚙️

Lazy Ranges

range() generates numbers on demand — perfect for huge loops.

🔢

Index + Value

enumerate() gives you both without manual counters.

👯

Parallel Walks

zip() walks several iterables together cleanly.

🚪

Clean Exit

Combine with break and the else clause for elegant searches.

Syntax

  • Basic form: for variable in iterable:
  • Use range() for numeric sequences without building a list.
  • Use enumerate() to get index and value together.
  • Use zip() to walk through several iterables in parallel.
  • Add an else block that runs when the loop completes without break.
For Loop — Syntax
# 1) Iterate over any sequence
for item in iterable:
    # work with item

# 2) Numeric range
for i in range(start, stop, step):
    print(i)

# 3) Index + value
for idx, val in enumerate(my_list):
    print(idx, val)

# 4) Parallel iteration
for x, y in zip(list_a, list_b):
    print(x, y)

Detailed Explanation

  • Iterables vs iterators: Anything that has an __iter__ method is iterable. A for loop hides this complexity — you simply write for x in collection and Python takes care of the rest.
  • range(start, stop, step): range() produces lazily-evaluated integers. It is memory-efficient — range(1_000_000) uses just a few bytes. stop is exclusive.
  • enumerate(): When you need both the index and the value, never write for i in range(len(lst)). Use enumerate(lst) — it's faster and far more idiomatic.
  • zip() for parallel loops: Pair two or more iterables: for name, age in zip(names, ages). Stops at the shortest iterable; use itertools.zip_longest to keep going.
  • Looping over dictionaries: By default, for k in d iterates over keys. Use d.values() or d.items() for values or key-value pairs.
  • The for-else clause: Add else: at the same indent level as for. The else block runs when the loop ends without hitting a break — ideal for 'not found' messages.

Code Examples

Example 1 — Iterate Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Output apple
banana
cherry
Example 2 — range() with step
for i in range(0, 11, 2):
    print(i, end=' ')
Output 0 2 4 6 8 10
Example 3 — enumerate() in Action
students = ["Riya", "Ankit", "Meera"]
for index, name in enumerate(students, start=1):
    print(index, name)
Output 1 Riya
2 Ankit
3 Meera
Example 4 — Looping Over a Dictionary
marks = {"Math": 95, "Science": 88, "English": 92}
for subject, score in marks.items():
    print(subject, "=>", score)
Output Math => 95
Science => 88
English => 92
Example 5 — Parallel Iteration with zip()
names = ["Anu", "Vivek", "Sara"]
ages  = [21, 24, 19]
for n, a in zip(names, ages):
    print(f"{n} is {a} years old")
Output Anu is 21 years old
Vivek is 24 years old
Sara is 19 years old
Example 6 — for-else: Search Pattern
nums = [3, 7, 11, 19, 23]
target = 8
for n in nums:
    if n == target:
        print("Found!")
        break
else:
    print("Not found")
Output Not found

Real-World Use Cases

Log Analysis

Loop through millions of log lines and count error patterns.

Spreadsheet Processing

Use openpyxl/pandas to iterate over rows and apply business rules.

Mail Merge

Send personalised emails by iterating over a contact list.

Web Scraping

Walk through scraped HTML elements and extract structured data.

Reporting

Aggregate KPI metrics from each row of a dataset.

Batch Operations

Apply transforms to every image, video or audio file in a folder.

Notes & Pro Tips

  • Use direct iteration (for x in lst) — avoid for i in range(len(lst)).
  • Combine enumerate() with start=1 for human-friendly numbering.
  • zip() halts at the shortest sequence; use itertools.zip_longest if you need padding.
  • Inside dict loops, .items() is the most explicit and self-documenting.
  • List comprehensions are often faster and clearer than explicit for loops for simple transforms.
  • Use break + the else clause to express 'search-and-fallback' logic.

Common Mistakes

  • Modifying the list you're iterating: creates skipped items; iterate over list[:] or use a comprehension.
  • Misunderstanding range: range(1, n) stops at n-1.
  • Using indices needlessly: prefer enumerate over manual counters.
  • Forgetting .items() on dicts: for k, v in d: raises ValueError.
  • Inefficient lookups in the loop body: compute constants outside the loop.
  • Misplaced else: it belongs at the for-block indent level, not inside it.

Practice Problems

  • Problem 1: Print all even numbers from 1 to 50 using range().
  • Problem 2: Reverse a string using a for loop without slicing.
  • Problem 3: Count how many times each letter appears in a given word.
  • Problem 4: Compute the dot product of two equal-length lists using zip().
  • Problem 5: Print a multiplication table from 1 to 10 in a clean grid using nested for loops.
  • Problem 6: Read a list of student names and print 'Topper: ' for the highest scorer.

Interview Questions

  • Q1. How does Python's for loop differ from C-style for loops?
  • Q2. What is the purpose of enumerate()? Show an example.
  • Q3. When would you use zip() over a plain for?
  • Q4. Can you iterate over a dictionary directly? What does it yield?
  • Q5. What does the else block on a for loop mean?
  • Q6. Why is iterating with for x in range(len(lst)) considered unidiomatic?

Frequently Asked Questions

  • Q1: Does range() create a list?
    No. range() returns a lazy range object. Convert it to a list with list(range(...)) only when you really need a list.
  • Q2: How can I get both index and value?
    Use enumerate(my_list) — it produces (index, value) pairs.
  • Q3: Can I loop over a string character by character?
    Yes. for c in 'hello' yields h, e, l, l, o one character at a time.
  • Q4: What happens if I change the list while looping?
    Indices shift and items may be skipped. Iterate over my_list[:] (a copy) or build a new list with a comprehension.
  • Q5: Is the for-else block really useful?
    Yes — especially for search loops where you want to do something only if no match was found. Place else at the for indent level.
  • Q6: Are for loops faster than while loops?
    Usually yes for known iterables, because for is optimised and avoids extra condition checks each iteration.

Summary

The Python for loop is a powerful, expressive tool that abstracts iteration over any data source. Combine it with range(), enumerate(), zip(), and the else clause to write loops that are short, readable, and Pythonic. Master these idioms and you'll spot exponential improvements in your code quality and execution speed.

Continue Learning

Previous

Go to Previous Chapter

Next

Go to Next Chapter