Python program to Reverse a range in list


When it is required to reverse a given range in a list, it is iterated over and the ‘:’ operator along with slicing is used to reverse it.

Example

Below is a demonstration of the same

my_list = ["Hi", "there", "how", 'are', 'you']

print("The list is : ")
print(my_list)

m, n = 2, 4

my_result = []
for elem in my_list:
   my_result.append(elem[m : n + 1])

print("The sliced strings are : " )
print(my_result)

Output

The list is :
['Hi', 'there', 'how', 'are', 'you']
The sliced strings are :
['', 'ere', 'w', 'e', 'u']

Explanation

  • A list is defined, and is displayed on the console.

  • Two variables with values are defined.

  • An empty list is defined.

  • The original list is iterated over, and elements are appended to the empty list.

  • This is done using the ‘:’ operator and accessing the elements from the given variables range.

  • The output is displayed on the console.

Updated on: 20-Sep-2021

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements