user813030
user813030

Reputation: 19

Python - Why can't I use generators inside the print function?

my code:

a=[3,3,3,3,3,3,45,4,5,2,2,4,3,3,3,3]
print(x for x in set(a))

output:

<generator object <genexpr> at 0xb62dccec>

why? And how can I print the set using one line?

Upvotes: 1

Views: 173

Answers (3)

Mureinik
Mureinik

Reputation: 311188

printing just prints the object (which is a generator), it does not consume its data. You could convert it to a list and thus print its values:

a = [3,3,3,3,3,3,45,4,5,2,2,4,3,3,3,3]
print([x for x in set(a)])
# here^-----------------^

Upvotes: 2

FHTMitchell
FHTMitchell

Reputation: 12157

You don't need a generator. Just print the set as is:

print(set(a))

If you want to do something with each item use

print(*(something(x) for x in set(a)), sep=', ')  # unpacks generator, bare

or even

print({something(x) for x in set(a)})  # creates new set, surrounded by {}

or

print([something(x) for x in set(a)])  # creates new list, surrounded by []

Upvotes: 3

Remolten
Remolten

Reputation: 2682

You can print it like this:

print(set(a))

The reason your current code doesn't work is because the print function doesn't consume generator objects.

Upvotes: 2

Related Questions