Reputation: 543
I am trying to rearrange the order of elements in a list.
I want to move the element at i + 1 position to the end of the list,
for len(list) - 2 times.
For example if I have
>>> 5 6 7 8 9 10 11 12 13 14 15
5 7 8 9 10 11 12 13 14 15 6
5 7 9 10 11 12 13 14 15 6 8
5 7 9 11 12 13 14 15 6 8 10
5 7 9 11 13 14 15 6 8 10 12
5 7 9 11 13 15 6 8 10 12 14
5 7 9 11 13 15 8 10 12 14 6
5 7 9 11 13 15 8 12 14 6 10
5 7 9 11 13 15 8 12 6 10 14
5 7 9 11 13 15 8 12 6 14 10 # desired output
Below is my code, but I just cannot figure out a way to remove the i + 1th element from the list and append it at the end of the list.
The code returns an error saying that pop index out of range and its quite frustrating.
def rearrange(sequence):
test_list = list(sequence)
length = len(test_list)
for i in range(length - 2):
stray_element = test_list.pop(i + 1)
test_list.append(stray_element)
Upvotes: 1
Views: 168
Reputation: 4653
The code you posted (after editing it to make it return, and providing an input sequence) works fine for me and produces the desired output.
my_sequence = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def rearrange(sequence):
test_list = list(sequence)
length = len(test_list)
for i in range(length - 2):
stray_element = test_list.pop(i + 1)
test_list.append(stray_element)
return test_list
print(rearrange(my_sequence))
outputs:
[5, 7, 9, 11, 13, 15, 8, 12, 6, 14, 10]
(posted as an answer rather than a comment mainly because of formatting...)
Upvotes: 2