[Tutor] Reordering a list
Magnus Lyckå
magnus@thinkware.se
Fri May 30 14:41:05 2003
At 10:00 2003-05-30 -0700, Alan Colburn wrote:
>In other words, if list=["one","two","three"] and the
>user selects "two" from the list box (i.e., list[1]),
>and clicks the "Up" button, then the list will become
>list=["two","one","three"].
First of all, don't use builtin names such as 'list'
as variable names. I assume you use some better name
in your program, I just thought I'd mention this once
more... :) Suddenly you need to do l2 = list(t2), and
that won't work as expected if you redefined the name
'list'.
Over to the code:
>>> l=["two","one","three"]
>>> l[1],l[2] = l[2],l[1]
>>> l
['two', 'three', 'one']
>>>
So, you could write functions like...
>>> def swapInList(l, x, y):
... l[x], l[y] = l[y], l[x]
...
>>> def moveUpInList(l, x):
... swapInList(l, x, x-1)
...
>>> l = range(5)
>>> l
[0, 1, 2, 3, 4]
>>> moveUpInList(l, 3)
>>> l
[0, 1, 3, 2, 4]
>>> moveUpInList(l, 2)
>>> l
[0, 3, 1, 2, 4]
moveDownInList is left as an exercise for the reader...
--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program