For Loops
For Loops
For loops are one of the most powerful and commonly used features in Python. They allow you to iterate over sequences like lists, strings, ranges, and other iterable objects.
For loops are preferred when you know how many times you want to iterate or when you're iterating over a collection of items. They're more Pythonic and often more readable than while loops for these cases.
For Loop with range()
The range() function generates a sequence of numbers, perfect for creating loops that run a specific number of times:
Iterating Over Sequences
For loops can iterate over any sequence: strings, lists, tuples, and more:
Using enumerate() for Index and Value
When you need both the index and value, use enumerate():
Loop Control: break and continue
You can control for loops with break (exit) and continue (skip to next iteration):
Nested For Loops
You can nest for loops to work with multi-dimensional data or create patterns:
The else Clause in For Loops
For loops can have an else clause that executes after the loop completes normally (not via break):
Practical Examples
Here are some common real-world uses of for loops:
Range Function Details
💡 Range Function Forms
• range(stop) - from 0 to stop-1
• range(start, stop) - from start to stop-1
• range(start, stop, step) - with step size
💡 Important Notes
• Range is exclusive on the stop value (doesn't include it)
• Range doesn't create a list - it's an iterator (memory efficient)
• To see the values, convert to list: list(range(5))