Is profitability too often called mail?

In the following code, the counter loops with two lists of elements. I expected the counter to be called twice, but it is called three times. Why?

def equivalent_count(start=0, step=1):
    """From python docs for itertools.count."""
    n = start
    while True:
        print('count in loop =', n)
        yield n
        n += step

c = equivalent_count()
l = [0, 1]

for i, j in zip(c, l):
    pass

Output:

count in loop = 0
count in loop = 1
count in loop = 2

Documents for zipstate, "The iterator stops when the shortest input iterable is exhausted."

+4
source share
2 answers

Change cand l:

for i, j in zip(l, c):
    pass

to get only two prints:

count in loop = 0
count in loop = 1 

Now lexhausted, but next(c)not called a third time, as in your version.

+2
source

c l, Python , l . , l :

def gen_l(lst):
    for l in lst:
        print 'gen_l called'
        yield l

c = equivalent_count()
l = gen_l([0, 1])
for i, j in zip(c, l):
    pass

:

count in loop = 0
gen_l called
count in loop = 1
gen_l called
count in loop = 2
+3

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


All Articles