The for Loop in Python 3
🟢 Beginner Level | Sequence Traversal
📖 Definition
The for loop in Python iterates over the items of any sequence (such as a list, tuple, string, or range object) in the order that they appear.
🤔 Purpose
Unlike traditional counter-based loops in C, Python's for loop acts as a high-level iterator, eliminating manual index management when traversing collections.
🌐 Multilingual Explanations
English
Python's for variable in iterable: syntax assigns each element of the iterable sequentially to variable and runs the indented code block.
Hindi
Python mein for item in list: syntax har item ko बारी-बारी item variable mein hold karke block ko execute karta hai. Numerical counting ke liye range(start, stop, step) use hota hai.
Marathi
Python madhye for loop cha wapar sequence madhil pratyek element varan jaanyasathi kela jato. Index chi garaj naste.
Hinglish
Collection iteration ke liye for item in collection: best pythonic pattern hai. range(5) 0 se 4 tak integer stream generate karta hai.
📝 Syntax & Parameters
for item in sequence:
# Indented body statements
pass
⚡ Execution Flow
- Python requests an iterator from the
sequenceobject. - For each element, Python binds it to
item. - The indented loop body executes with
itembound to the current value. - When
StopIterationis encountered, the loop completes naturally.
💡 Progressive Examples
Example 1: Sequence Iteration
frameworks = ["Django", "FastAPI", "Flask"]
for fw in frameworks:
print(f"Backend framework: {fw}")
Example 2: Range Counting
for i in range(1, 4):
print(f"Counting: {i}")
🖥️ Expected Output
Backend framework: Django
Backend framework: FastAPI
Backend framework: Flask
Counting: 1
Counting: 2
Counting: 3
🔍 Line-by-Line Code Breakdown
frameworks = [...]: Instantiates list of string objects.for fw in frameworks:: Sequentially binds each element to local variablefw.print(f"..."): Formats and outputs string representation.
⚠️ Variations & Edge Cases
Python supports a for...else clause: the else block executes ONLY if the loop completes without hitting a break statement!
❌ Common Beginner Mistakes
Modifying List While Iterating: Mutating (adding or removing elements from) a list while iterating over it with a for loop causes skipped elements or unexpected behavior.
🛠️ Real-World Practical Usage
Data processing and filtering:
prices = [19.99, 5.50, 100.00, 45.00]
discounted = []
for p in prices:
if p > 20.0:
discounted.append(p * 0.9)
print("Discounted prices:", discounted)
🎯 Tiered Practice Exercises
- Beginner: Write a `for` loop printing numbers from 10 down to 1 using `range()`.
- Intermediate: Write a `for` loop that counts the number of vowels in a given string.
- Advanced: Use `enumerate()` inside a `for` loop to print both index positions and values of a list.