Reputation: 1975
I need to move single or multiple sequential items in a list, by sequential I mean if the items are more than one there are no gaps in their list indexes, here is what I have tried...
def move(x, tomove, idx):
move_start = tomove[0]
move_end = tomove[-1] + 1
if idx == len(x) or idx == len(x) - 1:
return x[:move_start] + x[move_end:] + x[move_start:move_end]
elif idx == 0:
return x[move_start:move_end] + x[:move_start] + x[move_end:]
else:
pass
# move to start
print (move([0,1,2,3,4,5,6],
[2],
0))
# expected output [2,0,1,3,4,5,6]
# move to end
print (move([0,1,2,3,4,5,6],
[2],
6))
# expected output [0,1,3,4,5,6,2]
# move forward single
print (move([0,1,2,3,4,5,6],
[2],
3))
# expected output [0,1,3,2,4,5,6]
# move backward single
print (move([0,1,2,3,4,5,6],
[2],
1))
# expected output [0,2,1,3,4,5,6]
# move forward multiple
print (move([0,1,2,3,4,5,6],
[2,3],
5))
# expected output [0,1,4,5,2,3,6]
# move backward multiple
print (move([0,1,2,3,4,5,6],
[4,5],
2))
# expected output [0,1,4,5,2,3,6]
Upvotes: 1
Views: 82
Reputation: 169
Since you've not mentioned anything about validation like if the given sequence of elements is not present in the original list, the ordering of the main list and given list etc. I've not considered any validations.
Before jumping into code, let's see how to crack the solution. First, you need to identify the existing position of the given list in the main list.
move_list_pos = lis.index(move_list[0])
Now, check whether the given list to be moved forward or backward.
Solution code:
def move(lis,move_list,pos):
move_list_pos = lis.index(move_list[0])
if pos<move_list_pos:
return lis[:pos]+move_list+lis[pos:move_list_pos]+lis[move_list_pos+len(move_list):]
else:
return lis[:move_list_pos]+lis[move_list_pos+len(move_list):pos+1]+move_list+lis[pos+1:]
Upvotes: 1