Returning every element from a list (Python)

luisamaria picture luisamaria · Dec 3, 2014 · Viewed 46k times · Source

I know that it is possible for a function to return multiple values in Python. What I would like to do is return each element in a list as a separate return value. This could be an arbitrary number of elements, depending on user input. I am wondering if there is a pythonic way of doing so?

For example, I have a function that will return a pair of items as an array, e.g., it will return [a, b].

However, depending on the input given, the function may produce multiple pairs, which will result in the function returning [[a, b], [c, d], [e, f]]. Instead, I would like it to return [a, b], [c, d], [e, f]

As of now, I have implemented a very shoddy function with lots of temporary variables and counts, and am looking for a cleaner suggestion.

Appreciate the help!

Answer

wenzul picture wenzul · Dec 3, 2014

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