Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
range() FunctionIn many traditional programming languages like C or Java, a for loop is built around manual index arithmetic: initializing an integer i = 0, checking a boundary i < n, and incrementing i++.
In Python, the for loop is vastly more elegant. It is fundamentally a collection iterator (commonly known as a for-each loop). It iterates directly over the items of any sequence or iterable—such as lists, tuples, strings, dictionaries, or ranges—automatically handling start, step, and termination without requiring manual index manipulation.
+-------------------------------------------------------------------------------+
| FOR LOOP REAL-WORLD ANALOGIES |
+-------------------------------------------------------------------------------+
1. THE MUMBAI DABBAWALA SORTING CRATE:
- At Churchgate station, a Dabbawala stands before a wooden delivery crate:
crate = ["Tiffin #101 (Nariman Pt)", "Tiffin #102 (Fort)", "Tiffin #103 (Colaba)"]
- FOR each tiffin IN crate:
* Read destination alphanumeric marking.
* Load onto designated bicycle carrier.
- The Dabbawala doesn't need to manually count "Index 0, Index 1, Index 2";
they naturally take each tiffin box until the crate is completely empty.
2. ISRO ROCKET LAUNCH COUNTDOWN:
- Sriharikota Launch Control:
- FOR second IN range(10, 0, -1):
* Announce remaining seconds: "T-minus 10... T-minus 9... T-minus 1..."
- Main engine ignition commands ignite at 0!
+-------------------------------------------------------------------------------+How data and code flow step-by-step
for...in StatementThe standard syntax is:
Python automatically extracts each successive element from the iterable, assigns it to <target_variable>, executes the indented block, and gracefully terminates once the sequence is exhausted.
range() FunctionWhen you need to execute code a specific number of times or generate arithmetic sequences of numbers, Python provides the built-in range() function.
A range object is memory-efficient because it generates numbers on-demand (lazy evaluation) rather than allocating a full list in memory.
range():Output:
range(start, stop) is inclusive of start but exclusive of stop. Hence, range(1, 5) yields 1, 2, 3, 4 (stops before 5).Strings are iterable sequences of characters:
enumerate() (Index + Value):When you require both the numerical index and the item value, avoid the anti-pattern for i in range(len(items)):. Instead, use the idiomatic Python built-in enumerate():
Output:
Output:
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
DO iterate directly over elements: for item in items:. | DON'T use C-style indexing: for i in range(len(items)): item = items[i] unless indices are explicitly needed for mutation. |
DO use enumerate(iterable, start=1) when indices are needed alongside elements. | DON'T maintain a manual counter i = 0; i += 1 inside a for loop. |
DO use range(start, stop, step) for arithmetic progressions and countdowns. | DON'T instantiate huge lists like list(range(10000000)) in memory when iterating; range itself is already lazy. |
DO use meaningful singular/plural variable names: for student in students:. | DON'T use single ambiguous letters like for x in data: for complex data structures. |
for loop iterates directly over elements of any iterable sequence (for-each semantics).range(start, stop, step) built-in creates a lazy arithmetic sequence generator:start defaults to 0.stop is exclusive.step defaults to +1 (can be negative for countdowns).range objects do not store all numbers in memory; they calculate items on-the-fly in $O(1)$ memory.enumerate(sequence) to retrieve (index, item) pairs simultaneously in an idiomatic and clean manner.If you forget to update your loop counter inside a while loop, the condition remains True forever:
Removing or inserting items in a list while looping over it causes skipped elements:
range(2, 10, 3)?A. 2, 5, 8, 11 B. 2, 5, 8 C. 2, 4, 6, 8, 10 D. 3, 6, 9
A. 15 B. 10 C. 5 D. 4
for loop when you need both the element and its zero-based index?A. zip() B. index() C. enumerate() D. counter()
A. 3 2 1 0 B. 3 2 1 C. 0 1 2 3 D. 2 1 0
for item in my_list: considered more Pythonic than for i in range(len(my_list)): item = my_list[i]?A. range(len()) is deprecated and removed in Python 3.12 B. Direct iteration is cleaner, less error-prone (no off-by-one errors), and works identically across non-indexable iterables like generators and sets C. Direct iteration compiles into C++ machine code D. Direct iteration automatically sorts the items in ascending order
Build an automated batch settlement engine for an Indian UPI payments aggregator (Razorpay / Paytm Payment Gateway).
The system receives a batch of daily retail UPI transactions. Each transaction record includes the merchant ID, payer VPA, transaction amount in INR, and payment mode ("UPI_QR", "UPI_CREDIT_CARD", or "UPI_P2M").
for and enumerate(transactions, start=1)."UPI_CREDIT_CARD": 1.8% of transaction amount."UPI_P2M" and "UPI_QR": 0.0% if amount <= Rs 2,000, else 0.5%.amount - mdr_fee).In the next lesson, we will continue your Python learning journey with Nested Loops (13: Loops).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| While Loop | Nested Loops |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.