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

Steven D'Aprano steve+comp.lang.python at
Mon Dec 23 01:45:46 CET 2013

Something funny is going on here, not only has the original gone missing,
but my reply apparently has also gone missing. Let me try again, and
apologies for if you see duplicate messages.

On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec... at 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 ?

There is no need for a function to swap two values. In Python, if you want
to swap two values (or three, or thirty-three for that matter!) just
reassign them all at once.

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

Python guarantees that after this, x will have the value that y had, and y
will have the value that x had. No need for a function!

To return two or more values from a function, use a tuple:

def sum_and_product(a, b):
    """Return the sum and product of a and b."""
    sum = a+b
    product = a*b
    return (sum, product)

s, p = sum_and_product(100, 2)

s will now have the value 102, and p the value 200.


More information about the Python-list mailing list