Pregunta

I have to return many variables from my function:

a = 5
b = 6
c = 8
d = 6
...
return a,b,c,d,e,f,g,h

Problem is that I would like to do it through array to save a code lines:

for (...):
  ar[x] = ... # For x = a,b,c,d,e, ...

But I have to return variables in format 'return a,b,c,d,e' and I do not want to write it as:

return ar[a], ar[b], ar[c], ...

So can I use a generator for it and how? Somethig like:

return item for item in len(ar)
¿Fue útil?

Solución

When you are "returning multiple variables", you are actually just returning a tuple. You can do this:

return tuple(ar)

or even

return ar

Assuming, of course, that your array contains everything you want to return in the correct order, and only that.

It would be nice to see more code, but it is likely that if you can fill that list using a loop, then it's semantically a single value (a homogenous collection) anyway.

Otros consejos

You can do this:

def func(x):
    # do something
    lis = (#your values)
    return lis
a,b,c,d,e = func(x)

This will return the values as a tuple, and unpacked at the other end

Use a generator expression and tuple:

return tuple(ar[x] for x in (a,b,c,d,e))

If indexes are continuous then you can use slicing:

return tuple(ar[2:8])   #If `ar` is a already a tuple then remove the tuple call

If you want to return the whole tuple/list itself then simply return it as is:

return ar   #or return tuple(ar)

Note that returning a tuple is not compulsory, more discussion on it here: Python: Return tuple or list?

def values():
    a = 3
    b = 5
    c = 9
    d = 3
    e = 5

    return(a, b, c, d, e)

a1 = values()
print list(a1)

and you can edit the above function to return the tuple of variables

tuple(a,b,c,d,e) 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top