|
| 1 | +```` |
| 2 | +π§ PYTHON ITERATION β BEHIND THE SCENES (BTS) |
| 3 | +============================================ |
| 4 | +
|
| 5 | +π― PURPOSE: |
| 6 | +------------ |
| 7 | +Understand how Python loops (like `for`) work behind the scenes using: |
| 8 | +- iter() |
| 9 | +- next() |
| 10 | +- Iterable and Iterator concepts |
| 11 | +
|
| 12 | +This helps write better loops, understand errors like StopIteration, and even build your own custom iterators! |
| 13 | +
|
| 14 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 15 | +1οΈβ£ ITERATION TOOLS β WHAT WE USE TO LOOP |
| 16 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 17 | +These are tools used to iterate in Python: |
| 18 | +
|
| 19 | +- for loops |
| 20 | +- list/set/dict comprehensions |
| 21 | +- while loops using manual next() |
| 22 | +- generator expressions |
| 23 | +
|
| 24 | +All these tools work on top of **iterable** objects. |
| 25 | +
|
| 26 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 27 | +2οΈβ£ ITERABLE OBJECTS β WHAT WE LOOP OVER |
| 28 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 29 | +An object is **iterable** if it can return items one at a time. |
| 30 | +
|
| 31 | +Examples of iterable objects: |
| 32 | +- list β [1, 2, 3] |
| 33 | +- string β "hello" |
| 34 | +- tuple β (1, 2, 3) |
| 35 | +- set, dict, file objects |
| 36 | +
|
| 37 | +Technically, they must define a method: |
| 38 | +```python |
| 39 | +__iter__() |
| 40 | +```` |
| 41 | + |
| 42 | +This method returns an **iterator** object. |
| 43 | + |
| 44 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 45 | +3οΈβ£ ITERATORS β WHO DOES THE REAL WORK |
| 46 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 47 | +An iterator is an object that: |
| 48 | + |
| 49 | +β
Has a method `__iter__()` β returns itself |
| 50 | +β
Has a method `__next__()` β returns the next item |
| 51 | +π« Raises `StopIteration` when all items are used |
| 52 | + |
| 53 | +Example: |
| 54 | + |
| 55 | +```python |
| 56 | +lst = [1, 2, 3] |
| 57 | +itr = iter(lst) |
| 58 | + |
| 59 | +print(next(itr)) # 1 |
| 60 | +print(next(itr)) # 2 |
| 61 | +print(next(itr)) # 3 |
| 62 | +print(next(itr)) # StopIteration Error |
| 63 | +``` |
| 64 | + |
| 65 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 66 | +4οΈβ£ HOW FOR LOOPS WORK INTERNALLY |
| 67 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 68 | +Code you write: |
| 69 | + |
| 70 | +```python |
| 71 | +for item in myList: |
| 72 | + print(item) |
| 73 | +``` |
| 74 | + |
| 75 | +Python translates it behind the scenes to: |
| 76 | + |
| 77 | +```python |
| 78 | +itr = iter(myList) |
| 79 | +while True: |
| 80 | + try: |
| 81 | + item = next(itr) |
| 82 | + print(item) |
| 83 | + except StopIteration: |
| 84 | + break |
| 85 | +``` |
| 86 | + |
| 87 | +π So `for` = `iter()` + repeated `next()` |
| 88 | + |
| 89 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 90 | +5οΈβ£ ITERABLE vs ITERATOR β WHATβS THE DIFFERENCE? |
| 91 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 92 | + |
| 93 | +| Feature | Iterable | Iterator | |
| 94 | +| ------------------ | -------- | -------- | |
| 95 | +| Has **iter** | β
| β
| |
| 96 | +| Has **next** | β | β
| |
| 97 | +| Remembers position | β | β
| |
| 98 | + |
| 99 | +Check using: |
| 100 | + |
| 101 | +```python |
| 102 | +from collections.abc import Iterable, Iterator |
| 103 | + |
| 104 | +print(isinstance([1,2,3], Iterable)) # True |
| 105 | +print(isinstance([1,2,3], Iterator)) # False |
| 106 | + |
| 107 | +print(isinstance(iter([1,2,3]), Iterator)) # True |
| 108 | +``` |
| 109 | + |
| 110 | +β οΈ `iter(myList) is myList` β False |
| 111 | +Because `iter()` returns a **new** iterator object. |
| 112 | + |
| 113 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 114 | +6οΈβ£ REAL-LIFE ANALOGY π§ |
| 115 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 116 | +Iterable = Playlist β You can restart anytime |
| 117 | +Iterator = Music Player β It plays one by one and remembers which song is playing |
| 118 | + |
| 119 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 120 | +7οΈβ£ FILE OBJECTS ARE ITERATORS π |
| 121 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 122 | +You can loop through files directly: |
| 123 | + |
| 124 | +```python |
| 125 | +with open("file.txt") as f: |
| 126 | + for line in f: |
| 127 | + print(line) |
| 128 | +``` |
| 129 | + |
| 130 | +Why? Because file objects implement both `__iter__()` and `__next__()`. |
| 131 | + |
| 132 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 133 | +8οΈβ£ CREATING CUSTOM ITERATORS π οΈ |
| 134 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 135 | +You can build your own iterator class using `__iter__()` and `__next__()`: |
| 136 | + |
| 137 | +Example: |
| 138 | + |
| 139 | +```python |
| 140 | +class CountUpto: |
| 141 | + def __init__(self, max): |
| 142 | + self.max = max |
| 143 | + self.current = 1 |
| 144 | + |
| 145 | + def __iter__(self): |
| 146 | + return self |
| 147 | + |
| 148 | + def __next__(self): |
| 149 | + if self.current > self.max: |
| 150 | + raise StopIteration |
| 151 | + val = self.current |
| 152 | + self.current += 1 |
| 153 | + return val |
| 154 | + |
| 155 | +# Usage |
| 156 | +for num in CountUpto(3): |
| 157 | + print(num) # 1, 2, 3 |
| 158 | +``` |
| 159 | + |
| 160 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 161 | +9οΈβ£ SUMMARY β KEY TAKEAWAYS β
|
| 162 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 163 | + |
| 164 | +- `for` loops use `iter()` to get an iterator, and `next()` to get each value. |
| 165 | +- `StopIteration` tells Python when to stop. |
| 166 | +- Iterables (like list, str, file) do not have memory of position. |
| 167 | +- Iterators remember where they left off. |
| 168 | +- File objects are their own iterators. |
| 169 | +- You can build custom iterators using Python classes. |
| 170 | + |
| 171 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 172 | +π PRACTICE QUESTIONS π¬ |
| 173 | +ββββββββββββββββββββββββββββββββββββββββββββ |
| 174 | + |
| 175 | +1. What does `iter()` return? |
| 176 | +2. Why is `iter(myList) is myList` False? |
| 177 | +3. What happens if we keep calling `next()` after the last item? |
| 178 | +4. What exception tells Python to stop a loop? |
| 179 | +5. What's the difference between an iterable and an iterator? |
| 180 | + |
| 181 | +π― Tip: Mastering this helps you understand how loops, generators, comprehensions, and file I/O work at a deeper level! |
| 182 | + |
| 183 | +``` |
| 184 | +
|
| 185 | +--- |
| 186 | +
|
| 187 | +Would you also like a **printable PDF version**, a **diagram**, or a **Roman Urdu explanation** for revision? |
| 188 | +``` |
0 commit comments