Difference in printing items of iterable
Question:
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
Answers:
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.
It’s because in the first example, you’re not looping over the individual items of an iterable to print()
them one by one; instead, you’re using comprehension to create an iterable and print()
the entire 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:
<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
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.
It’s because in the first example, you’re not looping over the individual items of an iterable to print()
them one by one; instead, you’re using comprehension to create an iterable and print()
the entire iterable.