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
elseblock that runs when the loop completes withoutbreak.
# 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. Aforloop hides this complexity — you simply writefor x in collectionand 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.stopis exclusive. - enumerate(): When you need both the index and the value, never write
for i in range(len(lst)). Useenumerate(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; useitertools.zip_longestto keep going. - Looping over dictionaries: By default,
for k in diterates over keys. Used.values()ord.items()for values or key-value pairs. - The for-else clause: Add
else:at the same indent level asfor. The else block runs when the loop ends without hitting abreak— ideal for 'not found' messages.
Code Examples
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
banana
cherry
for i in range(0, 11, 2):
print(i, end=' ')
students = ["Riya", "Ankit", "Meera"]
for index, name in enumerate(students, start=1):
print(index, name)
2 Ankit
3 Meera
marks = {"Math": 95, "Science": 88, "English": 92}
for subject, score in marks.items():
print(subject, "=>", score)
Science => 88
English => 92
names = ["Anu", "Vivek", "Sara"]
ages = [21, 24, 19]
for n, a in zip(names, ages):
print(f"{n} is {a} years old")
Vivek is 24 years old
Sara is 19 years old
nums = [3, 7, 11, 19, 23]
target = 8
for n in nums:
if n == target:
print("Found!")
break
else:
print("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) — avoidfor i in range(len(lst)). - Combine
enumerate()withstart=1for human-friendly numbering. zip()halts at the shortest sequence; useitertools.zip_longestif you need padding.- Inside dict loops,
.items()is the most explicit and self-documenting. - List comprehensions are often faster and clearer than explicit
forloops for simple transforms. - Use
break+ theelseclause 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 atn-1. - Using indices needlessly: prefer
enumerateover manual counters. - Forgetting
.items()on dicts:for k, v in d:raisesValueError. - 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
forloop differ from C-styleforloops? - Q2. What is the purpose of
enumerate()? Show an example. - Q3. When would you use
zip()over a plainfor? - Q4. Can you iterate over a dictionary directly? What does it yield?
- Q5. What does the
elseblock on aforloop 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