[Tutor] Reordering a list

Rick Pasotto rick@niof.net
Fri May 30 14:10:03 2003


On Fri, May 30, 2003 at 10:00:54AM -0700, Alan Colburn wrote:
> Hi all --
> 
> I'm working on a program that includes a list, displayed in order (the
> list is displayed in a PythonCard list box but, for purposes of this
> post, that's relatively unimportant ... just think of a standard
> list). 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. 
> 
> 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"]. 
> 
> 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?

If you want to move the item at index 'x':

one slot closer to the front of the list:

l.insert(x-1, l.pop(x))

one slot closer to the end of the list:

l.insert(x+1, l.pop(x))

-- 
"Exhilaration is that feeling you get just after a great idea hits you,
 and just before you realize what's wrong with it." -- Anonymous
    Rick Pasotto    rick@niof.net    http://www.niof.net