'How to print a generator expression?

In the Python shell, if I enter a list comprehension such as:

>>> [x for x in string.letters if x in [y for y in "BigMan on campus"]]

I get a nicely printed result:

['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']

Same for a dictionary comprehension:

>>> {x:x*2 for x in range(1,10)}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

If I enter a generator expression, I get not such a friendly response:

>>> (x for x in string.letters if x in (y for y in "BigMan on campus"))
<generator object <genexpr> at 0x1004a0be0>

I know I can do this:

>>> for i in _: print i,
a c g i m n o p s u B M

Other than that (or writing a helper function) can I easily evaluate and print that generator object in the interactive shell?



Solution 1:[1]

Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:

def gen():
    x = 0
    while True:
        yield x
        x += 1
g1 = gen()
list(g1)   # never ends

Also, reading a generator changes it, so there's not a perfect way to view it. To see a sample of the generator's output, you could do

g1 = gen()
[g1.next() for i in range(10)]

Solution 2:[2]

Or you can always map over an iterator, without the need to build an intermediate list:

>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM

Solution 3:[3]

You can just wrap the expression in a call to list:

>>> list(x for x in string.letters if x in (y for y in "BigMan on campus"))
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']

Solution 4:[4]

>>> list(x for x in string.letters if x in (y for y in "BigMan on campus"))
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']

Solution 5:[5]

Generator object do not store actual data, it is basically just an expression. Program can not print what will be value of an expression without evaluating it. Generator object(generator expression) can be evaluated by typecasting into any iterable data type.

eg.

list(genexpr)
dict(genexpr)
set(genexpr)
for data in genexpr: 

Additional

generating generator expression and then typecasting is 20% slower than directly creating required datatype object. So if we require whole data it's better to use

data=[x for x in range(0,10)]

than using

genexpr=(x for x in range(0,10))
data=list(genexpr)

Solution 6:[6]

print(i for i in range(9))

if we run this we will get output as: - <generator object at 0x000001F01A153E40>

one simple way to print generator is converting it to list. so simply if we modify our code as print(*[i for i in range(9)])

So we will get output as : 0 1 2 3 4 5 6 7 8

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chad
Solution 2 lbolla
Solution 3 Jean-François Fabre
Solution 4 Andreas Jung
Solution 5 DINBANDHU KUMAR
Solution 6 Nihal Jugel