3

I have a list of numbers, such as:

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

I'm having trouble figuring out how to switch the first 2 items of the list with the last 2, or the first 3 with the last 3, and so on.

When i assign the values of the 1st two numbers to the last 2 items of the list, i then cannot assign the last 2 values (what used to be the last 2 values of the list) to the first two because the last 2 values have been lost.

If i try using another empty list and appending the last 2 values of the original list to that list, then appending the middle values, and then the first 2 values of the old list, I end up with something like this:

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

I don't want nested lists! What I want is:

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

Can someone help me?

1
  • 2
    you're almost there with the second approach, except that you should extend the target rather than append to it. Commented Apr 6, 2013 at 11:34

1 Answer 1

10
>>> nums = [1, 2, 3, 4, 5, 6]
>>> nums[:2], nums[-2:] = nums[-2:], nums[:2]
>>> nums
[5, 6, 3, 4, 1, 2]

This modifies the original list but if you want a separate new list you should use the following:

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

Note: This won't work properly if your list has < 4 elements

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.