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

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

提交回复
热议问题