Reputation: 19
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
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
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
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