Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
enumerate(), zip(), reversed(), & sorted()In low-level programming languages, developers frequently write index-tracking variables, boundary conditions, and manual pointer arithmetic just to walk through arrays.
Python reimagines iteration from first principles. By providing high-level built-in iteration helpers—such as enumerate(), zip(), reversed(), and sorted()—Python allows you to write declarative, highly readable, and bug-resistant loops that operate directly on your data.
+-------------------------------------------------------------------------------+
| ITERATION HELPER REAL-WORLD ANALOGIES |
+-------------------------------------------------------------------------------+
1. THE JACKET ZIPPER (zip):
- A jacket zipper has two parallel rows of metal teeth.
- As the slider pulls up:
Tooth A1 locks with Tooth B1
Tooth A2 locks with Tooth B2
Tooth A3 locks with Tooth B3
- `zip()` brings two or more independent lists together in perfect
parallel lockstep.
2. THE SBI BANK TOKEN DISPLAY (enumerate):
- Customers stand in line: ["Mrs. Sharma", "Mr. Patel", "Dr. Khan"]
- As each customer walks to the teller, the electronic counter displays:
Token #1: Mrs. Sharma
Token #2: Mr. Patel
Token #3: Dr. Khan
- `enumerate()` pairs every item with its sequential index automatically.
3. METRO TRAIN RETURN VOYAGE (reversed):
- Delhi Metro Yellow Line: Samaypur Badli -> Kashmere Gate -> HUDA City.
- On the return journey, the train traverses stations in exact reverse order
without rebuilding or modifying the physical track (`reversed()`).
+-------------------------------------------------------------------------------+enumerate()When you need the position index of an item alongside the item itself, never use the old C-style anti-pattern:
start Parameter:By default, enumerate() starts counting at 0. You can pass a start keyword argument to begin at 1 (or any integer):
Output:
zip()When you have two or more related lists and need to iterate through them simultaneously, zip() combines them element-by-element into tuples:
Output:
zip() halts as soon as the shortest iterable is exhausted. Any remaining elements in longer iterables are discarded. To preserve all elements, use itertools.zip_longest() with a default fillvalue.reversed()To walk backward through a sequence without permanently reversing or mutating the original collection, use reversed():
Output:
sorted()The sorted() built-in generates a newly sorted sequence from any iterable (including lists, tuples, or sets) without altering the source data:
Output:
.items(), .keys(), .values()Python dictionaries provide three distinct view iterators:
Output:
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
DO use enumerate(seq, start=1) for human-facing numbered lists. | DON'T write for i in range(len(seq)): when you need both the index and value. |
DO use zip(a, b) to interlock parallel lists. | DON'T manually access parallel lists via list2[i] using an index variable. |
DO use reversed(seq) to iterate backwards non-destructively. | DON'T call seq.reverse() just to loop backward, as that permanently mutates the list in place! |
DO use dict.items() to loop through both keys and values cleanly. | DON'T iterate over dict.keys() and look up dict[key] on every cycle. |
enumerate(seq, start=0) yields (index, element) tuples, eliminating manual index counters.zip(seq1, seq2, ...) stitches multiple sequences in parallel; iteration halts when the shortest sequence is exhausted.reversed(seq) yields elements in reverse order without modifying the original sequence.sorted(seq, key=..., reverse=...) yields elements in sorted order without mutating the underlying collection.dict.items() provides clean tuple unpacking for dictionary keys and values simultaneously.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:
enumerate(fruits, start=1) yield on its first iteration if fruits = ["Mango", "Apple"]?A. (0, "Mango") B. (1, "Mango") C. "Mango" D. [1, "Mango"]
for x, y in zip(A, B): execute?A. 8 times B. 5 times C. 3 times D. Python raises a ValueError for mismatched lengths
reversed(my_list) differ from my_list.reverse()?A. reversed() mutates the list in place, while my_list.reverse() returns a new list B. reversed() returns a reverse iterator without modifying the original list, while my_list.reverse() reverses the original list in place C. reversed() only works on strings, while .reverse() works on lists D. There is no difference; they are exact aliases
d?A. for k in d.keys(): v = d[k] B. for i in range(len(d)): k = list(d)[i] C. for k, v in d.items(): D. for v in d.values(): k = d.get_key(v)
A. 1 Anu 2 Bob B. 0 Anu 1 Bob C. Anu 0 Bob 1 D. (0, Anu) (1, Bob)
Build an automated match innings scorecard synthesizer for an Indian Premier League (IPL) cricket match.
The match scoring system provides three parallel data lists recorded during the Mumbai Indians innings:
batsmen: Names of the batsmen who batted.runs_scored: Total runs scored by each batsman.balls_faced: Total balls faced by each batsman.zip() to iterate over batsmen, runs_scored, and balls_faced in parallel.enumerate(..., start=1) to track batting position order.$$\text{Strike Rate} = \left(\frac{\text{Runs Scored}}{\text{Balls Faced}}\right) \times 100$$ (Handle edge cases where balls faced is zero using ternary expression).
"[EXPLOSIVE]""[SOLID AGGRESSIVE]""[ANCHOR]"In the next lesson, we will continue your Python learning journey with List Comprehension (13: Loops).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Loops with Else | List Comprehension |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.