Hi folks,
   How do I pass a list by value to a function.

The foll: snippet of code produces the output as shown:

Code:
-----
def junk(x):
    x.append("20")
    return x

a = ["10"]
b = junk(a)

print b
print a


Output:
-------
>>> 
b =  ['10', '20']
a =  ['10', '20']

This indicates that the variable "a" was passed by reference because the
function alters its value in the main script.

However, the following code produces a slightly diff output:

Code:
-----

def junk(x):
    x = "30"
    return x

a = ["10"]
b = junk(a)

print "b = ", b
print "a = ", a

Output:
-------
>>> 
b =  30
a =  ['10']

In this case, "a" seems to be passed by value, because the value is
unchanged even after the call to the function.


Question is, in the 1st scenario, how do I forcefully pass the variable
by value rather than reference. Why is there a difference between the
two scenarios?

Cheers
Hans
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to