Python program to Reverse a range in list

Python program to Reverse a range in list

In this tutorial, we'll learn how to reverse a specific range in a list using Python.

Scenario: Given a list:

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

If we want to reverse the elements from index 2 to index 6, the resulting list should be:

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

Steps:

  1. Split the list into three parts: before, within, and after the specified range.
  2. Reverse the elements within the specified range.
  3. Join the three parts back together.

Python Code:

def reverse_range_in_list(lst, start_idx, end_idx): """ Reverses a specific range in a list. :param lst: The original list. :param start_idx: The starting index of the range (inclusive). :param end_idx: The ending index of the range (inclusive). :return: List with the specified range reversed. """ # Split list into three parts before_range = lst[:start_idx] within_range = lst[start_idx:end_idx+1] after_range = lst[end_idx+1:] # Reverse the elements within the range within_range = within_range[::-1] # Join the three parts back together return before_range + within_range + after_range # Example usage: lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] start_idx = 2 end_idx = 6 modified_list = reverse_range_in_list(lst, start_idx, end_idx) print(modified_list) # This should display [1, 2, 7, 6, 5, 4, 3, 8, 9] 

Explanation:

  • We define the function reverse_range_in_list that takes in a list lst, and two indices start_idx and end_idx.
  • We use list slicing to extract the elements of the list that come before the specified range, the elements within the range, and the elements after the range.
  • We then reverse the elements within the range using slicing with [::-1].
  • We join the three parts together using list concatenation to form the final list with the reversed range.
  • In the example usage, we call the reverse_range_in_list function with our sample list and the specified range indices, then print the result.

This method provides a clean and intuitive way to reverse a specific range in a list. By breaking the task into logical steps and using list slicing and concatenation, we can achieve the desired result with minimal code.


More Tags

windows webdriverwait urlencode picturebox tmx selection-sort sharing ssh-keys http2 next.js

More Programming Guides

Other Guides

More Programming Examples