Home > Back-end >  Python returns a generator object when trying to print?
Python returns a generator object when trying to print?

Time:10-27

So I'm trying to print using list comprehension where I want to print each element individually in iterations. The code in question:

str1 = "You don't know how amazing it is to learn how to program!"

list1 = str1.split(" ")

print(i.upper() for i in list1 if len(i) > 5)

But when I try to run the code it spits out:

<generator object <genexpr> at 0x000001F4212233C0>

And the desired output would be:

AMAZING
PROGRAM!

Other than using a normal for loop, what can I do here to achieve what I want using just one line of code inside of the print() function?

CodePudding user response:

The form

(i.upper() for i in list1 if len(i) > 5)

is a generator expression (a genexpr). It won't have a value until it's iterated, and print() doesn't iterate objects by itself. (It only makes strings out of them, and <generator object <genexpr>> is the string form of a generator expression.

To fix this, you have a couple of options (aside from using a list comprehension):

  • Use "\n".join() on the genexpr to make it a string joined by newlines:
    print("\n".join(i.upper() for i in list1 if len(i) > 5))
    
  • You can splat the generator expression into arguments for print with the * operator and tell print to separate values by newlines:
    print(*(i.upper() for i in list1 if len(i) > 5), sep="\n")
    

CodePudding user response:

You can put the generator expression inside join() to print each item on a line by itself:

print("\n".join(i.upper() for i in list1 if len(i) > 5))

which produces the desired output:

AMAZING
PROGRAM!

CodePudding user response:

The code inside the print statement would return a generator only. If you would like to get the desired output, try doing

print([i.upper() for i in list1 if len(i) > 5])

or

[print(i.upper()) for i in list1 if len(i) > 5]

CodePudding user response:

Your could try getting the output in an array

str1 = "You don't know how amazing it is to learn how to program!"
list1 = str1.split(" ")
print([i.upper() for i in list1 if len(i) > 5])
  • Related