Python List Advanced Exercise - Reverse a list at a specific location
1. Reverse List at Specific Location
Write a Python function to reverse a list at a specific location.
Sample Solution:
Python Code:
Sample Output:
Original list: [10, 20, 30, 40, 50, 60, 70, 80] Reverse elements of the said list between index position 2 and 4 [10, 20, 50, 40, 30, 60, 70, 80] Original list: [10, 20, 50, 40, 30, 60, 70, 80] Reverse elements of the said list between index position 6 and 7 [10, 20, 50, 40, 30, 60, 80, 70] Original list: [10, 20, 50, 40, 30, 60, 80, 70] Reverse elements of the said list between index position 0 and 7 [70, 80, 60, 30, 40, 50, 20, 10]
Algorithm: reverse_list_in_location(lst, start_pos, end_pos) function
Input: A list “lst” and two integers start_pos and end_pos indicate the start and end positions of the sub-list that needs to be reversed.
Output: The input list “lst” with the sub-list from start_pos to end_pos reversed.
Steps:
- Initialize two variables start_pos and end_pos to the start and end positions of the sub-list.
- While start_pos is less than end_pos do the following:
- Swap the elements at start_pos and end_pos
- Increment start_pos by 1
- Decrement end_pos by 1
- Return the list lst.
Flowchart:

What is the time complexity and space complexity of the following Python code?
Time complexity - The time complexity of the code is O(n), where n is the difference between "end_pos" and "start_pos". Due to the swapping of two elements at each iteration, the while loop iterates n/2 times. Therefore, the time complexity of the while loop is O(n/2), which is equivalent to O(n).
Space complexity - The space complexity of the code is O(1) because the algorithm modifies the input list in-place without creating any new data structures. As a result, the function uses the same amount (constant) of space regardless of the size of the input list.
For more Practice: Solve these Related Problems:
- Write a Python function that takes a list and an index, then returns a new list with the portion after that index reversed.
- Write a Python function to reverse only the elements between two specified indices in a list.
- Write a Python function to reverse the sublist starting from a given index to the end of the list in-place.
- Write a Python function that reverses every segment of a list separated by a specific delimiter value.
Go to:
Previous: Python List Advanced Exercise Home.
Next: Length of the longest increasing sub-sequence.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.