Thanks guys
 
Yes either of the foll solves the problem:
 
b = junk(copy.copy(a))
 OR

b = junk(a[:])
 
 
Why is there a difference between the way the two lines (x.append("20")  and x = "30") are handled within a function?

 

From: Adam [mailto:[EMAIL PROTECTED]
Sent: Tuesday, 6 December 2005 1:49 p.m.
To: Hans Dushanthakumar
Subject: Re: [Tutor] How to Pass lists by value

On 06/12/05, Hans Dushanthakumar <[EMAIL PROTECTED]> wrote:

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

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

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

That should give you what you're looking for a[:] will pass the values of a.

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

Reply via email to