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

list, python, return

Solution

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

Problem

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 instead or RETURN. If I use print it prints out the whole list in a column with "None" at the end of the list, but return will print out just the first item. Why? This is the code: ``` def union(a,b): a.append(b) for item in a: return item a=[1,2,3,4] b=[4,5,6] print union(a,b) ``` It returns: 1 If I use ``` def union(a,b): a.append(b) for item in a: print item a=[1,2,3,4] b=[4,5,6] print union(a,b) ``` instead, I get: 1 2 3 4 [4, 5, 6] None (and not even in a single line). Please note that I´ve found more results with this issue (like this one), but they are not quite the same, and they are quite complicated for me, I´m just beggining to learn to program, thanks!

Original source