I wonder it it is possiblibe to write function to swap two variables like in C

void swap (int* x, int*y)
    int temp;
    temp = *x;
    *y = temp;

I already tried with soemthing like this:

def swap (x, y):
    tmp = x
    x = y
    y = tmp

but it's not it....
Any thoughts?

You simply use tuple packing ...

a = 1; b = 2; c = 3
# swap a with b
a, b = b, a         # now b = 1 and a = 2
# multiple swaps
a, b , c = b, c, a  # now b = 1  c = 2  a = 3

... or if you want to, do it the much more complicated C way ...

def swap2(a, b):
    """swap the C way with a temp"""
    t = a
    a = b
    b = t
    return a, b

a = 1
b = 2
print "a = %d  b = %d" % (a, b)
a, b = swap2(a, b)
print "after swapping:"
print "a = %d  b = %d" % (a, b)

Try to do the multiple swap in C.

Try to do the multiple swap in C.

hehe, the only language I ever learned and used is C (C++) I assume I can't simply to wrap my mind to see how easy and elegant this is done in Python. That is reason why I left it two monts ago, but I'm back now...

This question has already been answered. Start a new discussion instead.