Home » Python » python – Is there a function to reverse an array, but only specific indexes?-Exceptionshub

python – Is there a function to reverse an array, but only specific indexes?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I need help to find a way to reverse a list. The only condition is to reverse specific index ranges. For example if my arr is [0,1,2,3,4,5,6,7], and you must reverse everything from index 2 to 5, then the end arr would be [0,1,5,4,3,2,6,7]? I code in Python3. Any help is appreciated!

How to&Answers:

To reverse indexes a to b, you can use the slice ([:]) operator and the function reversed():

l[a:b + 1] = reversed(l[a:b + 1])

Answer:

a = list(range(8))
a[0:2] + list(reversed(a[2:5])) + a[5:]

This should reverse only the specific portion that you want and welcome to Stackoverflow!