Iterables and iterators#
- An iterable is anything you can loop over: lists, strings, tuples, dicts, sets, files, ranges.
- An iterator is the object that actually produces the values one at a time and remembers where it is.
You get an iterator from an iterable with iter(), and ask for values with next():
How a for loop really works#
This for loop:
for f in fruits:
print(f)
is what Python does behind the scenes:
it = iter(fruits)
while True:
try:
f = next(it)
except StopIteration:
break
print(f)
Iterable = ऐसी चीज़ जिस पर loop चलाया जा सके (list, string, file...)।
Iterator = एक "pointer" जो याद रखता है कि अभी कहाँ तक पहुँचे हैं, और हर बार next() बोलने पर अगली value देता है।
इसे किताब और bookmark की तरह समझें - किताब (iterable) में सारे पन्ने हैं, bookmark (iterator) याद रखता है कि आप किस पन्ने पर हैं। जब पन्ने खत्म हो जाते हैं, तो StopIteration आता है और for loop अपने आप रुक जाता है।
Creating your own iterator class#
Implement two dunder methods:
__iter__()→ returns the iterator object (usuallyself)__next__()→ returns the next value, or raisesStopIteration
That's a lot of code for a simple idea. Generators make it much easier.
Generators and yield#
A generator function looks like a normal function but uses yield instead of return. Calling it doesn't run the code immediately - it returns a generator object that produces values on demand.
return vs yield#
return |
yield |
|---|---|
| sends one value and ends the function | sends a value and pauses the function |
| local variables are lost | local variables are remembered |
| function runs once | function resumes on each next() |
return = काम खत्म करके जवाब दे दो, function बंद।
yield = एक जवाब दो, लेकिन रुककर इंतज़ार करो - अगली बार माँगने पर ठीक वहीं से आगे शुरू करो जहाँ रुके थे।
जैसे चाय वाला: return = एक बार में पूरा 100 कप चाय का बर्तन दे देना (भारी, जगह चाहिए)। yield = ग्राहक जब माँगे, तब एक कप बनाकर देना - कम जगह, कम बर्बादी। इसीलिए generators बड़ी files और बड़े data के लिए बहुत उपयोगी हैं।
Why generators? Memory efficiency#
A list stores all values in memory. A generator stores only the current state:
Real-world use: processing a large file line by line#
def read_large_log(path):
with open(path) as f:
for line in f:
if "ERROR" in line:
yield line.strip()
for error in read_large_log("server.log"): # works even for a 10 GB file
print(error)
Infinite generators#
Generators can run forever - you take only what you need:
Generator pipelines#
Chain generators so each step processes one item at a time:
Useful tools: itertools#
A generator can be consumed only once:
g = (x for x in range(3))
print(list(g)) # [0, 1, 2]
print(list(g)) # [] - already exhausted
Summary#
- Iterables can be looped over; iterators produce values with
next()and raiseStopIterationat the end. - A
forloop callsiter()once andnext()repeatedly. - Iterator classes implement
__iter__and__next__. - Generator functions use
yield; they pause and resume, keeping their state. - Generators are memory-efficient (one value at a time) and can be infinite; they can be consumed only once.