Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading