Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does zip on a generator return just one item?

I tried this in Python, thinking it would give me [(1,123),(2,123)]:

Python 2.7.3 (default, Feb 27 2014, 19:58:35)
>>> def my_generator():
...   yield 123
...
>>> zip([1,2], my_generator())
[(1, 123)]

Why does zip stop after creating just one item? Is there a Pythonic way to get what I was looking for?

like image 443
Doradus Avatar asked Mar 21 '23 06:03

Doradus


1 Answers

Create an infinite generator, like this

def my_generator():
    while True:
        yield 123
print zip([1,2], my_generator())
# [(1, 123), (2, 123)]

The better way to do this would be, using itertools.repeat, like this

from itertools import repeat
print zip([1,2], repeat(123))
# [(1, 123), (2, 123)]
like image 71
thefourtheye Avatar answered Apr 13 '23 00:04

thefourtheye