1

I have a question wether it is possible to reverse certain arrays in my 2D array. For example

a=[[1,2],[3,4],[5,6]] 
a[1:3].reverse()
print(a)

would output:

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

I hope you can help :)

2 Answers 2

2
a = [[1, 2], [3, 4], [5, 6]]
a = a[:1] + list(reversed(a[1:3]))
print(a)

You could also use pure slicing, but imo the previous version is more readable:

a = a[:1] + a[:-3:-1]
Sign up to request clarification or add additional context in comments.

1 Comment

to add explanation, a[1:3] creates a new list and because .reverse is an in-place method - a is not affected
0

Your code is actually reversing a copy, and not changing the underlying array.

I'd do this:

a[1:3] = reversed(a[1:3])

It takes a reversed copy of the elements from 1 to three and puts them into their initial locations.

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.