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

Difference in printing items of iterable

I am new to python. Why is there difference between the below given codes:

Code 1

iterable=filter(lambda x:x%2!=0,range(15))
print(i for i in iterable)

It gives:

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

<generator object <genexpr> at 0x7f23e37f35f0>

Code 2:

iterable=filter(lambda x:x%2!=0,range(15))
for i in iterable:
    print(i)

It gives:

1
3
5
7
9
11
13

I believed both of these printing methods were same till now. Why is there a difference in the outputs?
Thanks

>Solution :

print(i for i in iterable)

In this line, the i for i in iterable is a generator-expression i.e. an expression that results in a generator when evaluated.

The result you see is the generator that was created by the expression. Generators are lazily evaluated. They yield values when you iterate over them. So print() on a generator doesn’t yield the values immediately.

for i in iterable:
    print(i)

Here you are iterating over an iterable & printing each value individually, which means you get all the values in the result. There is no other generator involved.

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