Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the output of a generator [duplicate]

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))
like image 528
user3012727 Avatar asked Jan 21 '26 05:01

user3012727


1 Answers

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.

like image 81
eumiro Avatar answered Jan 23 '26 19:01

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!