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:
<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.