0

Here i want to generate 5 dicts, where 'a' is index 'i', 'b' is a random int between 0 and 5. But result stuck at 'a'=0, it kept generate new c from random.randint(0,5) and 'i' remained the same. how to fix this? thx a lot

def wdg():
    for i in range(5):
        c = random.randint(0,5)
        yield {'a':i,'b':c}

next(wdg())
  • Can you please be specific about the problem you are encountering? – juanpa.arrivillaga Nov 01 '21 at 13:04
  • 5
    If you do `next(wdg())` over and over you're gonna create a new generator object every time. Instead assign it to something (`gen = wdg()`), and then do `next(gen)`. – L3viathan Nov 01 '21 at 13:05
  • 1
    Your program is terminating after the first `yield`. To get all of the values a generator is capable of generating, you have to iterate over it. `for result in wdg(): print (result)` – BoarGules Nov 01 '21 at 13:09
  • thx a lot, (gen = wdg()), and then do next(gen) can do the job – johnyanccer Nov 01 '21 at 13:24

1 Answers1

3

Assign generator to a variable for example 'generator'. Then each time you call next(generator) one execution will occur, leading to increment i by one and generate random c:

generator = wdg()
print(next(generator))
Przemosz
  • 101
  • 5