Python: Why “return” won´t print out all list elements in a simple for loop and “print” will do it?

前端 未结 4 926
醉话见心
醉话见心 2021-01-15 05:10

Im trying to print out all elements in a list, in Python, after I´ve appended one list to another. The problem is that it only prints out every element when I use PRINT inst

4条回答
  •  日久生厌
    2021-01-15 05:36

    The return statement will, as the name suggests, make the function return, thus stopping any iteration of the surrounding for loop (in your code, the for loop will iterate only once).

    If you want to return the result of the two "concatenated" lists, as a single list, this will work:

    def union(a,b):
        a.append(b)
        return a
    

    If you expected the return to behave differently, probably you are confusing it with the yield keyword to make generator functions?

    def union(a,b):
        a.append(b)
        for item in a:
            yield item
    
    a=[1,2,3,4]
    b=[4,5,6]
    for i in union(a, b):
        print i
    

    This code will also print every element in the list resulting from appending b to a.

    Basically, what the yeld does, is suspend the current execution of the method, which will resume the next time starting from after the yield itself (until the StopIteration will be risen because the items in a will be finished).

提交回复
热议问题