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

梦想的初衷 提交于 2019-12-01 13:16:48

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

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
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

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).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!