Returning every element from a list (Python)
There is a yield statement which matches perfectly for this usecase.
def foo(a):
for b in a:
yield b
This will return a generator which you can iterate.
print [b for b in foo([[a, b], [c, d], [e, f]])
When a python function executes:
return a, b, c
what it actually returns is the tuple (a, b, c)
, and tuples are unpacked on assignment, so you can say:
x, y, z = f()
and all is well. So if you have a list
mylist = [4, "g", [1, 7], 9]
Your function can simply:
return tuple(mylist)
and behave like you expect:
num1, str1, lst1, num2 = f()
will do the assignments as you expect.
If what you really want is for a function to return an indeterminate number of things as a sequence that you can iterate over, then you'll want to make it a generator using yield
, but that's a different ball of wax.