0

Can someone please explain to me why there is a difference in printing my sequence generation between "with" and "without" a for loop?

def generation(x):
    i = 0
    while i < x:
        yield i
        i += 1

x = generation(10)
print("Print without for loop: " + str(x))

print("Print with for loop: ")
for j in x:
    print(j)
Prune
  • 76,765
  • 14
  • 60
  • 81

1 Answers1

1

Your first print prints the generator object. Your second print invokes the generator, iterating through the yielded values.

This is much like the difference between printing the value of a function object (handle) and calling the function.

I think that you're perhaps misinterpreting the semantics of your first print. To get the list of integers in that form, you'd need something that iterates through the generator:

print("Print as list")
print (list(generation(10)))
Prune
  • 76,765
  • 14
  • 60
  • 81
  • Just `list(generation(10))` works. There's no need for a list comprehension. – Blckknght Aug 11 '17 at 00:08
  • Good point. I was trying to parallel OP's usage. Now that I see it in print, the `list` operation is better. Answer is upgraded. – Prune Aug 11 '17 at 00:13