How can i return more than one value from a function to more than one variable

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Dec 22 19:37:24 EST 2013


Unfortunately, the original post seems to have gone missing here, so 
please excuse me for breaking threading.

On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec... at msn.com wrote:
> basically what I wanna do is this :
> 
> x = 4
> y = 7
> 
> def switch (z,w):
> ***this will switch z to w and vice verca***
>     c= z
>     z=w
>     w=c
>     print 'Now x =', w, 'and y = ' , z
>     return w
>
> x = switch(x,y)
> 
>
>  How am I supposed to do so I can  return also a value to the variable
>  y WITHOUT printing 'Now x =', w, 'and y = ' , z   a second time ?


To swap two values in Python (or for that matter, three or thirty-three 
values!) just re-assign the values. Python guarantees that this will work:

x = 23
y = 42
x, y = y, x

x now has the value that y had, and y has the value that x had. There is 
no need for a temporary value, and no need for a "switch" function.

To return more than one value from a function, return a list or a tuple. 
Normally we use a tuple:


def sum_and_product(x, y):
    sum = x + y
    product = x*y
    return (sum, product)


a = 100
b = 2
s, p = sum_and_product(a, b)

Now s will have the value 102 and p will have the value 200.




-- 
Steven



More information about the Python-list mailing list