Easy questions from a python beginner

Terry Reedy tjreedy at udel.edu
Mon Jul 12 02:13:05 EDT 2010


On 7/11/2010 1:48 PM, wheres pythonmonks wrote:

> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
> = 7; swap(x,y);" given x=7,y=3??
> (I want to use Perl's Ref "\" operator, or C's&).
> (And if I cannot do this [other than creating an Int class], is this
> behavior limited to strings,
>   tuples, and numbers)

Since you are just exploring, addendum to other answers:

 >>> x,y = 1,2
 >>> def swapxy():
	global x,y
	x,y=y,x

 >>> swapxy()
 >>> x,y
(2, 1)

Not too useful

 >>> s = [1,2]
 >>> def swap01(lis):
	lis[:2] = reversed(lis[:2]) # other versions possible

 >>> swap01(s)
 >>> s
[2, 1]

A function can *modify* an input object. When is does, the usual 
convention is that it should *not* return the object.

-- 
Terry Jan Reedy




More information about the Python-list mailing list