0

New to Python, with some background in C & Javascript.

I have the following two functions and test cases:

def switch(a, b):
    print("switch__You gave me (%d, %d)." % (a,b))
    y = a
    a = b 
    b = y
    print("switch__The order is now (%d, %d)" % (a, b))

def sortHi_Low(c, d):
    print("SORT You gave me (%d, %d)." % (c,d))
    if (c < d):
        switch(c, d)
        print("SORT The order is now (%d, %d)" % (c, d))
    else:
        print("SORT The order did not change (%d, %d)" % (c, d))

print("Case 1 \n")
sortHi_Low(10, 3)

print("\nCase 2 \n")
sortHi_Low(4,5)

switch() works as anticipated. sortHi_Low()runs switch(), but always returns the numbers in the same order they have been passed in.

My understanding with Python is that objects are always passed by reference. When switch took in the sort's variables as parameters, it should have changed their value by reference - then the sort should have returned those new values. However, this is what prints in the interpreter.

Case 1

SORT You gave me (10, 3).
SORT The order did not change (10, 3)

Case 2

SORT You gave me (4, 5).
switch__You gave me (4, 5).
switch__The order is now (5, 4)
SORT The order is now (4, 5)

The sort should go Hi to Low, but does not work.

Naltroc
  • 989
  • 1
  • 14
  • 34
  • 1
    Your understanding is [wrong](http://effbot.org/zone/call-by-object.htm) – Wayne Werner Oct 18 '16 at 01:22
  • Briefly: `switch(c, d)` doesn't change `c` and `d` because everything in `switch` is a local variable. – TigerhawkT3 Oct 18 '16 at 01:24
  • Also see [this question about passing objects by reference](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference). – TigerhawkT3 Oct 18 '16 at 01:25
  • Also note: Python `tuple` packing and sequence unpacking make swapping so trivial it's not worth factoring out into a separate function: `a, b = b, a` is the canonical way to swap, requiring no temporary names at all. – ShadowRanger Oct 18 '16 at 01:27
  • [This answer](http://stackoverflow.com/questions/34139424/call-destructor-of-an-element-from-a-list/34140055#34140055) is related and should help you, too. Also read [this article](http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/). – Rick Oct 18 '16 at 08:39

0 Answers0