Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning every element from a list (Python)

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!

like image 913
luisamaria Avatar asked Dec 03 '14 00:12

luisamaria


People also ask

How do you return every element in a list Python?

Practical Data Science using Python Any object, even a list, can be returned by a Python function. Create the list object within the function body, assign it to a variable, and then use the keyword "return" to return the list to the function's caller.

What does return {} mean in Python?

The Python return keyword exits a function and instructs Python to continue executing the main program. The return keyword can send a value back to the main program. A value could be a string, a tuple, or any other object. This is useful because it allows us to process data within a function.


2 Answers

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]])
like image 103
wenzul Avatar answered Sep 20 '22 22:09

wenzul


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.

like image 44
Lee Daniel Crocker Avatar answered Sep 21 '22 22:09

Lee Daniel Crocker