3

When I run the code I get the following output

How do I print the print the output?

def firstn(n):
    num=0
    while num < n:
        yield num
        num=num+1


sum_of_first_n=sum(firstn(10))
print(firstn(3))
eumiro
  • 207,213
  • 34
  • 299
  • 261
user3012727
  • 41
  • 1
  • 4

2 Answers2

2

In general:

print(list(firstn(n)))

Be sure your generator is not infinite. If you are not sure, use something like:

import itertools as it

print(list(it.islice(firstn(n), 100)))

to print up to the first 100 elements.

eumiro
  • 207,213
  • 34
  • 299
  • 261
1

There's different ways of doing that, but basically you have to iterate through the iterator. The simplest way is probably using list comprehension:

print(list(firstn(3)))

but if you wish you could write a for loop to do that (and get it fx one element per line):

for e in firstn(3):
    print(e)

One should however be aware that iterating through the generator consumes it and if you don't have means of retrieving a new generator (for example if you got the generator as parameter to a function call) you would have to store the values - fx in an array:

l = list(firstn(3))

for e in l:
    print(e)

for e in l:
    do_something(e)
skyking
  • 13,817
  • 1
  • 35
  • 57