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:
Pythona[start:end] = a[start:end][::-1]
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)
[1, 2, 7, 6, 5, 4, 3, 8, 9, 10]
Explaination:
Let's see other different methods to reverse a range in list.
Using Python's reversed() FunctionPython’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)
[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 LoopWe 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)
[1, 2, 7, 6, 5, 4, 3, 8, 9, 10]
Explaination:
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)
[1, 2, 7, 6, 5, 4, 3, 8, 9, 10]
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4