Home > other >  python print returns generator object instead of object itself
python print returns generator object instead of object itself

Time:01-29

Its a python silly problem and I am curious for the logic behind it.

num = 256

print(int(k) for k in str(num))

Above code returns:

<generator object <genexpr> at 0x00000160728DDBC8>

If I wrap the complete thing into a list then:

print([int(k) for k in str(num)])

Now it returns:

[2, 5, 6]

Now my question is why the below code return an generator object instead of object of the "num" variable.

print(int(k) for k in str(num))

CodePudding user response:

Because int(k) for k in str(num) is a generator and you are asking to print it. While [int(k) for k in str(num)] list comprehensions creates a list with the generated objects and when you are asking to print it you naturally get the list with the generated objects.

If you wrote [print(int(k)) for k in str(num)] instead you would get the output:

2
5
6

CodePudding user response:

When you are using an inline for loop in your print function, you create a generator object. You have to iterate through the generator object to actually get the items. When you wrap it into a list, it's called list comprehension, and the generator is iterated through into the list's items.
So, to print all the digits, you can do print(*(int(k) for k in str(num))) (or better: print(*map(int, str(num)))). Doing this will unpack the generator into seperate arguments for the print function. You can also just use str.join (print(", ".join(num)))

  •  Tags:  
  • Related