[Tutor] Reordering a list
Jeff Shannon
jeff@ccvcorp.com
Fri May 30 13:51:59 2003
Alan Colburn wrote:
>[...] What I'm trying to figure out is how
>to be able to rearrange the list at will --
>specifically, at the push of a button marked "Up" the
>currently highlighted list element will be moved up
>one place, and the previous list element will be moved
>down one place.
>
>[...]
>I've figured out a successful way to do this, but my
>procedure is cumbersome -- I know there must be an
>easier way ... but I don't know what it is. Any
>suggestions?
>
Well, I'm not sure what your "cumbersome" method might be, but the
obvious way to switch two list elements (at indices a and b) is this:
mylist[a], mylist[b] = mylist[b], mylist[a]
This in essence constructs a temporary tuple containing the values of
the two list elements, and then unpacks that tuple back into the same
locations but in reversed order. You may need some care to properly
specify the correct indices to use -- you'd move "up" the list by
swapping the selected element with the previous one (i.e., b = a - 1),
but what happens when the selected element is already at the top? If
you don't special-case this, then "up" from the top (mylist[0]) will
wrap around to the bottom (mylist[-1]), which may or may not be desired
behavior... but using a similar naive method to move down from the
bottom (b = a + 1) won't wrap around to the top, and will in fact cause
IndexError exceptions. You can solve these issues by putting safeguards
in your swapping code, or by simply disabling the "up" button when the
topmost item is selected and the "down" button when the bottommost item
is selected, or you can do both -- which is probably the best alternative.
Jeff Shannon
Technician/Programmer
Credit International