Open In App

Python program to reverse a range in list

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Reversing a specific range within a list is a common task in Python programming that can be quite useful, when data needs to be rearranged. In this article, we will explore various approaches to reverse a given range within a list. We'll cover both simple and optimized methods.

One of the simplest way to reverse a range in list is by Slicing.

Example: Suppose we want to reverse a given list 'a' from index 2 to 6.

Syntax:

a[start:end] = a[start:end][::-1]


Output
[1, 2, 7, 6, 5, 4, 3, 8, 9, 10]

Explaination:

  • a[start:end] extracts a segment of the list a from index start to end (excluding end).
  • [::-1] reverses the extracted segment.
  • The reversed segment is then replace back into the original segment in the list.

Let's see other different methods to reverse a range in list.

Using Python's reversed() Function

Python’s built-in reversed() function is another way to reverse a range. However, reversed() returns an iterator, so it needs to be converted back into a list.


Output
[1, 2, 7, 6, 5, 4, 3, 8, 9, 10]

Explanation:

  • a[2:7] extracts the sublist from index 2 to 6.
  • reversed(a[2:7]) creates an iterator that reverses the extracted sublist.
  • list(reversed(a[2:7])) converts the reversed iterator back into a list
  • Replace the original slice with the reversed list.

Note: This method is slightly longer than slicing directly but still effective.

Using a Loop

We are also reverse a range in a list by looping through the specified indices. This method provide us more control to use custom logic during reversal.


Output
[1, 2, 7, 6, 5, 4, 3, 8, 9, 10]

Explaination:

  1. Keep start & end pointers for the beginning and ending index of the reverse range respectively.
  2. Swap the elements at the start and end pointers.
  3. Increment start by 1 and decrement end by 1.
  4. Repeat step 2 and 3, until start pointer is smaller than end pointer.

Using List Comprehension

We can also use list comprehension to reverse a range, although this is less common than the other methods mentioned.


Output
[1, 2, 7, 6, 5, 4, 3, 8, 9, 10]

Explanation:

  • Use range(end, start - 1, -1) to iterate from the end index to start in reverse order.
  • Construct the reversed list and assign it back to the corresponding part of the original list.

Which Method to Choose?

  • Slicing Method: It is very concise, efficient, and easy to read. It works for most of the situations.
  • reversed() Function: It is useful if we prefer readability and want to use the built-in functions.
  • Loop Method: It provides more control for custom logic during reversal.
  • List Comprehension: This method is very less readable and more complex and it is not ideal for simple reversal tasks.

Next Article
Practice Tags :

Similar Reads