Question

I have a complex variable like the one below...

test_list[[test1, test1_var1, test1,var2], [test2, test2_var1]]

I have written a function to extract the variables from the desired test, see below...

def find_test(test_list, search_term):
    for index in range(len(test_list)):
        if test_list[index][0] == search_term:
            return test_list[index][1:]

This returns something like the following...

[test1_var1, test1_var2]

I would like to be able to return the variables as individual variables and not elements of a list. How would I go about doing this? How do I return variable number of variables? (sort of like *args but for return instead of arguments)

Was it helpful?

Solution 2

actually you can do what you want, by using a list:

def find_test(test_list, search_term):
    for index in range(len(test_list)):
        if test_list[index][0] == search_term:
            return test_list[index][1:]

the destructuring array syntax is there for you:

foo, bar = find_text(x, y)

if you want to get the result as a list you can:

l = find_text(x,y)

if you want to get only one element:

foo, _ = find_text(x,y)
_, bar = find_text(x,y)

if you like to read, here are a few resources:

OTHER TIPS

In python, returning multiple variables corresponds to returning any iterable, so there's no practical difference between returning a list or "multiple variables":

def f():
    return 1,2
def g():
    return [1,2]
a,b=f()
c,d=g()

The only difference between these two functions is that f returns a tuple, and g returns a list - which is indifferent, if you use multiple assignment on the return value.

Just use the built-in filter and expand the results in your function call:

def search(haystack, needle):
    return filter(lambda x: x[0] == needle, haystack)[0][1:]

a,b = search(test_list, 'test1')

Keep in mind if your result is more than two items, the above will fail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top