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

前端 未结 4 884
醉话见心
醉话见心 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:17

    When you use a return statement, the function ends. You are returning just the first value, the loop does not continue nor can you return elements one after another this way.

    print just writes that value to your terminal and does not end the function. The loop continues.

    Build a list, then return that:

    def union(a,b):
        a.append(b)
        result = []
        for item in a:
            result.append(a)
        return result
    

    or just return a concatenation:

    def union(a, b):
        return a + b
    
    0 讨论(0)
  • 2021-01-15 05:23
    def union(a,b):
        a.extend(b)
        for item in a:
            print item,
        return a
    
    
    a=[1,2,3,4]
    b=[4,5,6]
    union(a,b)
    

    prints

    1 2 3 4 4 5 6
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-15 05:40

    return means end of a function. It will only return the first element of the list.

    For your print version, a.append(b) makes a = [1,2,3,4,[1,2,3]] so you will see the elements before None. And the function returns nothing, so print union(a, b) will print a None.

    I think you may want:

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

    Or

    def union(a, b):
        return a + b
    
    0 讨论(0)
提交回复
热议问题