Joey
Joey

Reputation: 934

reordering a list based on specific order

I want to reorder a list with length n, where n can be any integer between 5 and 20.

example list = [1,2,3,4,5,6]

for each one of my generated lists, I want to move the last but one element [-2] to the start of the list [0] such that the final order becomes:

new_list = [5,1,2,3,4,6]

I have tried:

myorder =[1,2,3,4,5,6]


new_order = [(myorder[-2]), [i for i in myorder[:-2]], (myorder[-1])]

but this gives me a list in a list:

[5, [1, 2, 3, 4], 6]

Is there a simple way to do this for list comprehension?

Upvotes: 1

Views: 213

Answers (4)

DavidPM
DavidPM

Reputation: 475

You can try this:

new_order = [myorder[-2]] + [i for i in myorder[:-2]] + [myorder[-1]]

Or, simplifying a bit,

new_order = [myorder[-2]] + myorder[:-2] + [myorder[-1]]

Upvotes: 2

offeltoffel
offeltoffel

Reputation: 2801

I think this is the most general way of doing it:

example_list.insert(0, example_list.pop(-2))

You erase (pop) item -2 and insert it at position 0.

Upvotes: 1

RoadRunner
RoadRunner

Reputation: 26315

What about this:

>>> lst = [1, 2, 3, 4, 5, 6]
>>> lst = [lst[-2]] + lst[:-2] + [lst[-1]]
>>> lst
[5, 1, 2, 3, 4, 6]

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

You can use list slicing.

Ex:

l = [1,2,3,4,5,6]
print([l[-2]] + l[:-2] + l[-1:])

Output:

[5, 1, 2, 3, 4, 6]

Upvotes: 2

Related Questions