# Scope troubles with a swap function

Matthew D. Wood woodm at equire.com
Fri Aug 10 22:14:08 CEST 2001

```Ok, so swap works, just like you said it should.  (I'm still mad that I
didn't see that.)

however, the next project is to write a 'cycle_variables' function (or
single line like you did before.)

So, this time, we take an arbitrary number of variables, and cycle them
through.

def cycle (*vars) :
print 'Cycling the variables...'
vars = list(vars)
print vars
temp = vars[0]
for index in range(len(vars) - 1) :
vars[index] = vars[index + 1]

vars[-1] = temp
print vars
print 'See, I cycled them!'

A = 'a'
B = 'b'
C = 'c'
D = 'd'

print """Here's the original set:"""
print (A, B, C, D)
print

cycle(A, B, C, D)

print
print (A, B, C, D)
print """Oh, I guess I didn't really cycle them afterall."""

Obviously, that example doesn't work.  Is there a way to make it work?
I don't necessarily know if such a function would be all that usefull,
but I can't sleep at night because I haven't been able to figure out the
solution.  (That's a little exageration  :'-(   )

And once again, thanks for all you guys/gals who have helped me out.

Hans Nowak wrote:

>> ===== Original Message From "Matthew D. Wood" <woodm at equire.com> =====
>> Ok, I've been banging my head against this for a sufficiently long time
>> that I feel justified in presenting this personal challenge to the list.
>>
>> How do you make a swap function?
>
>
> You don't need to. :)  Use:
>
>   a, b = b, a
>
>> How do you make a function or a callable object instance that will do
>> what the following code intends to do:
>>
>>   def swap (heaven, hell) :
>>           purgatory = heaven
>>           heaven = hell
>>           hell = purgatory
>
>
> Python's internal workings are very different from languages like C and
> Pascal. A Python "variable" is not a location in memory that you can fill with
> arbitrary data. This Pascal code:
>
>   X := 3;
>   X := 42;
>
> changes the value of X, which resides at a certain location in memory. But the
> equivalent Python code
>
>   x = 3
>   x = 42
>
> does not do exactly the same; rather, it binds the name 'x' to the value 3,
> then rebinds that name to the value 42. Other people explain this better than
> me; see
>
>   http://w1.132.telia.com/~u13212494/guides/python-objects.htm
>
> HTH,
>
> --Hans Nowak
>
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20010810/56f3caaa/attachment.html>
```