1. Introduction
A for loop in Python repeats a block of code once for each item in an iterable — such as a list, tuple, string, dictionary, or the range() function. Unlike C-style for loops that manage an explicit counter with a condition and increment, Python's for loop is fundamentally a 'for-each' loop: it directly walks through the elements of whatever iterable you give it.
Cricket analogy: A fielding coach doesn't manually count 'ball one, ball two, ball three' while running catching drills — they simply run the drill once for every ball in the bucket, working through each one directly rather than tracking a counter.
This design makes for loops concise and less error-prone, since there is no separate counter variable to initialize, compare, and increment manually.
Cricket analogy: This is why a scorer using a pre-printed scoresheet with numbered overs already laid out makes fewer errors than one manually tallying overs on a blank pad, since there's no separate counter to misalign.
2. Syntax
for item in iterable:
# runs once per element in iterable
statement(s)
else:
# optional: runs only if the loop completed without a 'break'
statement(s)3. Explanation
On each pass, the loop variable (item above) is bound to the next element produced by the iterable, and the indented block executes with that value. When the iterable is exhausted, the loop ends automatically — there's no need to check a stopping condition yourself. For loops work with any iterable: lists, tuples, strings (iterating characters), dictionaries (iterating keys by default), sets, and generators.
Cricket analogy: As the coach works through the bucket, each ball (the loop variable) is placed in hand one at a time for the fielder to catch, and once the bucket is empty the drill ends automatically — it works whether the bucket holds cricket balls, tennis balls, or cones for footwork.
Python's for loop also supports an optional else clause, which is a feature unique among mainstream languages.
Cricket analogy: Unlike most drills, a fielding coach's routine has a bonus twist: if every ball in the bucket is caught cleanly without a single drop, the whole squad gets a rare reward at the end — a bonus stage most other coaching drills don't include.
The for-else clause: the else block after a for loop runs only if the loop finished normally, without hitting a break statement. It's commonly used for 'search' patterns — e.g., searching a list and running else only if the item was never found.
Avoid modifying a list while iterating over it directly with a for loop (e.g., removing items inside the loop). This can skip elements or cause unexpected behavior. Instead, iterate over a copy (for x in list(original):) or build a new list with a list comprehension.
4. Example
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
target = "banana"
for fruit in fruits:
if fruit == target:
print(f"Found {target}!")
break
else:
print(f"{target} not in list")5. Output
0: apple
1: banana
2: cherry
Found banana!6. Key Takeaways
- Python's for loop is a for-each loop that iterates directly over elements of any iterable.
- There is no manual counter management — the loop variable is assigned automatically each pass.
- enumerate() gives both index and value when you need positional information.
- The optional for-else clause runs only if the loop was not stopped by a break.
- Avoid mutating a list while looping over it directly; iterate over a copy instead.
- for loops work uniformly across lists, strings, dicts, sets, tuples, and generators.
Practice what you learned
1. What does 'for x in range(5):' iterate over?
2. When does the else clause of a for-else loop execute?
3. What does enumerate(['a', 'b']) yield?
4. What is the danger of writing 'for x in my_list: my_list.remove(x)'?
5. Which of these is NOT iterable with a for loop in Python?
Was this page helpful?
You May Also Like
while Loop in Python
Learn how Python's while loop repeats code as long as a condition stays True, and how to avoid infinite loops.
range() Function in Python
Learn how Python's built-in range() function generates sequences of numbers efficiently for use in loops.
break, continue and pass in Python
Master Python's three loop control statements: break to exit early, continue to skip an iteration, and pass as a no-op placeholder.
List Comprehension in Python
A concise Python syntax for building lists from iterables in a single expression, including conditionals and the memory-difference vs generator expressions.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics