3

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, so its just like doing say, list(), or tuple()
1

On Python 3, zip behaves same as Python2's izip. On Python2, izip returns a generator while zip returns a list, izip would be better in memory(doesn't create a new list.).

4 Comments

I meant builtin zip behaves same as Python2's izip. Fixed the wording, thanks.
@EdgarAroutiounian: The second sentence is directly relevant. And should you move on to Python 3 (which is a much better language than Python 2), the first one is as well.
@TimPietzcker Without meaning to start a dispute, simply hearing over and over that people should move to Python3 is just not cutting it anymore. Many people can't simply move to 3 and for many 3 is a failure. robg3d.com/?p=1175 lucumr.pocoo.org/2014/1/5/unicode-in-2-and-3 alexgaynor.net/2013/dec/30/about-python-3
@EdgarAroutiounian: Thank you for these interesting links! I still think that Py3k is much better, but I also see how the transition is difficult for many.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.