Python For Loops
Python · Loops
Theory
A for loop runs its block once for each item of an iterable: a list, tuple, string, set, dict, range, file or any other object that can hand out items one at a time. In for month in ['Jan', 'Feb', 'Mar']:, the name month is bound to 'Jan' for the first pass, then 'Feb', then 'Mar', and the loop ends when the items run out. Behind the scenes Python calls iter() on the object to get an iterator and then next() repeatedly until it raises StopIteration.
range(n) produces the numbers 0 to n-1 without building a list: range(2, 10, 3) gives 2, 5, 8, and the stop value is never included. enumerate(items) gives (index, item) pairs, and zip(a, b) walks two sequences side by side, which beats writing for i in range(len(items)). The loop variable keeps its last value after the loop ends. Avoid adding or removing items in a list while looping over that same list; it skips items. Loop over a copy or build a new list instead.
Why we use it
Almost every data task repeats an action for each item: each row, each file, each customer. A for loop does that without counters or index bookkeeping, and works on any iterable.
When to use it
Use for when you are processing every item of a collection or a known number of repetitions with range(). Use while when you repeat until a condition changes and do not know the count in advance. For building a new list, a comprehension is often shorter.
How it works
- for month in months: begins
- Python calls iter(months) to get an iterator
- Call next() on the iterator
- Did it return an item? Yes: Bind it to month and run the loop body. No: StopIteration: leave the loop.
- After the body, go back for the next item
- Loop done; output: Jan, Feb, Mar
Syntax
for item in iterable:
...Example
for month in ["Jan","Feb","Mar"]:
print(month)Key points
- Works on any iterable, not just lists
- range(n) generates 0..n-1; the stop value is never included
- Use enumerate() for index + item, zip() for parallel lists
- Do not add or remove items of the list you are looping over
- The loop variable keeps its last value after the loop