Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant use of generators? (Python)

say we did the following: (ignore if this is silly or if there is a better way, it's a simplified example)

from itertools import izip

def check(someList):
    for item in someList:
        yield item[0]

for items in izip(check(someHugeList1), check(someHugeList2)):
    //some logic

since check is a generator, is it redundant to use izip? Would using regular zip be just as good?


1 Answers

Regular zip() would expand the whole generator first. You wouldn't want to do that with a huge or endless generator.

Demo:

>>> def gen():
...     print 'generating'
...     yield 'a'
... 
>>> gen()
<generator object gen at 0x10747f320>
>>> zip(gen(), gen())
generating
generating
[('a', 'a')]

Note that directly creating the generator doesn't print anything; the generator is still in the paused state. But passing the generator to zip() immediately produces output, which can only be produced by iterating over the generators in full.

like image 133
Martijn Pieters Avatar answered Dec 01 '25 01:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!