Returning each item from a list (Python)

I know that a function can return multiple values ​​in Python. What I would like to do is return each item in the list as a separate return value. This can be an arbitrary number of items, depending on user input. I'm wondering if there is a pythonic way to do this?

For example, I have a function that will return a couple of items as an array, for example will return [a, b]

.

However, depending on the input entered, the function can generate multiple pairs, which will cause the function to return [[a, b], [c, d], [e, f]]

. Instead, I would like it to return[a, b], [c, d], [e, f]

At the moment I have implemented a very crappy function with a lot of temporary variables and counts, and I am looking for a cleaner suggestion.

Appreciate help!

+3


source to share


4 answers


There is a yield statement that is perfect for this utility.

def foo(a):
    for b in a:
        yield b

      



This returns a generator that you can iterate through.

print [b for b in foo([[a, b], [c, d], [e, f]])

      

+4


source


When python function is executed:

return a, b, c

      

what it actually returns is a tuple (a, b, c)

, and tuples are unpacked on assignment, so you can say:

x, y, z = f()

      

and everything's good. Therefore, if you have a list

mylist = [4, "g", [1, 7], 9]

      



Your function can simply:

return tuple(mylist)

      

and behave as you expect:

num1, str1, lst1, num2 = f()

      

will perform tasks as you expect.

If you really want the function to return an indefinite number of things as a sequence that you can iterate over, then you will want to make it a generator with yield

but a different ball of wax.

+2


source


Check out this question: How to return multiple values ​​from * args?

The important idea is that the return values, if they are a container, can be expanded into separate variables.

0


source


However, depending on the input entered, the function can create 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]

Can't you use the returned list (ie the list [[a, b], [c, d], [e, f]]) and extract the elements from it? Seems to fit your criteria for an arbitrary number / multiple values.

0


source







All Articles