Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the content of the generator?

N = [1, 2, 3]
print(n for n in N)

Results:

<generator object <genexpr> at 0x000000000108E780>

Why didn't it print?:

1
2
3

However the code:

sum(n for n in N) 

Will sum up all the number in N.

Could you please tell me why sum() worked but print() failed?

like image 657
chentaocuc Avatar asked Jun 18 '17 14:06

chentaocuc


3 Answers

It's because you passed a generator to a function and that's what __repr__ method of this generator returns. If you want to print what it would generate, you can use:

print(*N, sep='\n') # * will unpack the generator

or

print('\n'.join(map(str, N)))

Note that once you retrieve the generator's output to print it, the generator is exhausted - trying to iterate over it again will produce no items.

like image 96
Szymon Avatar answered Sep 17 '22 23:09

Szymon


If you don't want to cast it as a list, you can try:

print(*(n for n in N))

See: https://docs.python.org/3/tutorial/controlflow.html#tut-unpacking-arguments

like image 24
Charles Clayton Avatar answered Sep 21 '22 23:09

Charles Clayton


You are literally printing a generator object representation

If you want on one line, try printing a list

print([n for n in N])

Which is just print(N)

If you want a line separated string, print that

print("\n".join(map(str, N))) 

Or write a regular loop and don't micro optimize the lines of code

like image 27
OneCricketeer Avatar answered Sep 21 '22 23:09

OneCricketeer