Jean Marcos
Jean Marcos

Reputation: 167

Why my generator always returns the same value?

I am implementing examples of generators with python3, and this does not work when using the next():

def rgb():
    for r in range(256):
        for g in range(256):
            for b in range(256):
                yield r, g, b

for x in range(5):
    print(next(rgb()))

Output:

(0, 0, 0)
(0, 0, 0)
(0, 0, 0)
(0, 0, 0)
(0, 0, 0)

Now, if I use the for works:

def rgb():
    for r in range(256):
        for g in range(256):
            for b in range(256):
                yield r, g, b

for x in rgb():
    print(x)

Upvotes: 1

Views: 573

Answers (1)

hfhc2
hfhc2

Reputation: 4391

You seem to be misung the next() function in this case, you create a new instance of the rgb() function everytime. Try this:

def rgb():
    for r in range(256):
        for g in range(256):
            for b in range(256):
                yield r, g, b

it = rgb()
for x in range(5):
    print(next(it))

This prints

(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 0, 3)
(0, 0, 4)

as expected.

Upvotes: 3

Related Questions