Why does the zip on the generator return only one element?

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 only one item is created? Is there a way for Pythonic to get what I was looking for?

+4
source share
1 answer

Create an endless generator like this

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

The best way to do this is to use itertools.repeat, for example

from itertools import repeat
print zip([1,2], repeat(123))
# [(1, 123), (2, 123)]
+7
source

Source: https://habr.com/ru/post/1531265/


All Articles