tags:

views:

45

answers:

4

so I list mList = ['list1', 'list2', 'list8', 'list99']

I want to choose a value in that list say 'list8' and have it so that it is the first entry in the list ['list2', 'list1', 'list8', 'list99']

how do I reorder just this one entry all I can think of at the moment is -get the index -remove that entry -insert(0, entry)

what is a clean way to do this?

cheers..

A: 

Not sure I understood the question right, but this approach may work

mList = ['list1', 'list2', 'list8', 'list99']
idx = 2
mlist.insert(0, mlist.pop(idx))

will yield:

['list8', 'list1', 'list2', 'list99']

Here is another way:

mList = ['list1', 'list2', 'list8', 'list99']
value = 'list8'    
mlist.remove(value)
mlist.insert(0, value)
recursive
+2  A: 

Your approach is reasonable, but I would use remove directly on the value rather than first finding the index and then removing:

mList.remove('list2')
mList.insert(0, 'list2')

Note that these operations are inefficient on a list. It is more efficient to append to the end of the list than insert at the beginning. You might want to use a different data structure such as linked list. Another alternative is to reverse the order in which you store the elements.

Mark Byers
did not know about removeing directly, this is nicer, th lists will only have <100 entries
t_s
Your suggestion to use a linked list in Python is intriguing. How might one do that?
jathanism
@jathanism: http://stackoverflow.com/questions/2154946/python-linked-list-o1-insert-remove
Mark Byers
A: 
def move_up(val, lst):
    lst.insert(0, lst.pop(lst.index(val)))
move_up('list8', mList)
Nathon
+2  A: 

Others have posted solutions that maintain the order of the items that are not moved to the front. If you don't care about that, just swapping the first item with the one you want to move to the front is faster.

mList = ['list1', 'list2', 'list8', 'list99']

i = mList.index('list8')
mList[0], mList[i] = mList[i], mList[0]

print mList   # ['list8', 'list2', 'list1', 'list99']
kindall