Home > Enterprise >  Generator-based for loop and list-based for loop turns out different output?
Generator-based for loop and list-based for loop turns out different output?

Time:09-14

Here is the code

def func(x):
    print(x)
    return x

for x in (func(i) for i in range(2)):
    print(x)
print('-'*20)

for x in [func(i) for i in range(2)]:
    print(x)

This is the output

0
0
1
1
--------------------
0
1
0
1

Why do they have the different result? i.e, what does python do about (i for i in range(2)) and [i for i in range(2)]

CodePudding user response:

With (func(i) for i in range(2)) you're creating a generator that is evaluated lazily (the func() isn't called immediately),

With [func(i) for i in range(2)] you first create list with list-comprehension (func() is called) and then you iterate over this list in for-loop.

  • Related