Search code examples
pythoniterator

next() call not iterating


var = 10
Constant = 10
def Gen():
    i = 1
    for x in range(var):
        yield i
        i +=1   
o = Gen()

c = next(o) * Constant

for i in range(var):
    print(c)

What I've tried and their errors:

c = {next(o)} * Constant
        #unsupported operand type(s) for *: 'set' and 'int'
c = int({next(o)}) * Constant
        #int() argument must be a string, a bytes-like object or a real number, not 'set'`

Expected output:

10
20
30
40 
...

Solution

  • When you call next() you are asking for just one value. Since you want to iterate on the values returned by your generator you may write a loop, or a set comprehension, for instance:

    c = {z * Constant for z in o}
    

    The syntax you used just got a single value, put it in a set, and tried to multiply the set by Constant.

    Side note: why a set and not a list?