Python program to reverse a range in list (original) (raw)

Last Updated : 14 Oct, 2024

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]

Python `

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

Reverse elements from index 2 to index 6

a[2:7] = a[2:7][::-1] print(a)

`

Output

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

**Explaination:

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

Table of Content

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.

Python `

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

Reverse elements from index 2 to index 6

a[2:7] = list(reversed(a[2:7])) print(a)

`

Output

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

**Explanation:

**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.

Python `

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

Define the start and end indices

start, end = 2, 6

Reverse the elements from index 2 to 6

while start < end:

# Swap elements at start and end
a[start], a[end] = a[end], a[start]

# Move the start index forward
start += 1

 # Move the end index backward
end -= 1

print(a)

`

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.

Python `

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

Define the start and end

start, end = 2, 6

Use list comprehension to create the reversed segment

a[start:end+1] = [a[i] for i in range(end, start - 1, -1)]

print(a)

`

Output

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

**Explanation:

Which Method to Choose?

Similar Reads