Search code examples
pythonreturngeneratorplotly-dashyield

Return several values inside for loop


I have a function that must return several values using a for loop. I do not wish to store the values inside a list or a dict. Because of the use of the return, I only get the first value. How can I return all values successively? I tried using generators and yield but I'm not sure how to use it.

here is the function:

import random

def my_function():
    for i in range(3):
        return(dict(x=[[random.randint(0,10)]], y=[[random.randint(0,10)]]), 0)

Are generators and the use of yield suited for my need?


Solution

  • Replace return by yield to create a generator:

    import random
    
    def my_function():
        for i in range(3):
            yield dict(x=[[random.randint(0,10)]], y=[[random.randint(0,10)]]), 0
    
    g = my_function()
    for d in g:
        print(d)
    

    Output:

    ({'x': [[0]], 'y': [[10]]}, 0)
    ({'x': [[0]], 'y': [[1]]}, 0)
    ({'x': [[3]], 'y': [[0]]}, 0)
    

    You can also use next to consume manually the next value:

    g = my_function()
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))  # Will raise a StopIteration exception
    

    Output:

    ({'x': [[4]], 'y': [[4]]}, 0)
    ({'x': [[4]], 'y': [[9]]}, 0)
    ({'x': [[7]], 'y': [[2]]}, 0)
    ...
    StopIteration: