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