Create a function that rearranges item in list and shifts the other items (Python) -


i'm trying write function in python re-arrange specified item, moved new position , other items shift in relation.

the function accepts 2 arguments:

old_index - current index of item new_index - index want item moved

let's have list:

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

i decide move letter 'f' before letter 'b'. means old_index = 5 , new_index = 1. after operation done, want letters shifted, not swapped, resulting in this:

list = ['a', 'f', 'b', 'c', 'd', 'e', 'g']

i've come following function:

def shift_letters(old_index, new_index):      shifted = list.index(list[old_index])     selected = list[old_index]     print 'selected', selected     list.insert(new_index, selected)     print 'inserted %s @ %s' % (selected, new_index)     if old_index < new_index:         removed = list.pop(shifted - 1)     else:         removed = list.pop(shifted + 1)      print 'removed %s' % removed 

but doesn't work well. i'd avoid making copies of list if possible (lists in application large).

pop old index, insert @ desired index.

>>> mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> old_index = 5 >>> new_index = 1 >>>  >>> mylist.insert(new_index, mylist.pop(old_index)) >>> mylist ['a', 'f', 'b', 'c', 'd', 'e', 'g'] 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -