[Tutor] How to Pass lists by value

Hans Dushanthakumar Hans.Dushanthakumar at navman.com
Tue Dec 6 02:04:10 CET 2005


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:adam.jtm30 at gmail.com] 
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 <Hans.Dushanthakumar at navman.com> 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 at 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.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20051206/c3bf2a2d/attachment.html


More information about the Tutor mailing list