Question 16 of 16intermediate🔧 ApplyLong Answer3 marks

Read a list of n elements. Pass this list to a function which reverses this list in-place without creating a new list.

Correct Answer

python def reverse_in_place(lst): left = 0 right = len(lst) - 1 while left < right: lst[left], lst[right] = lst[right], lst[left] left += 1 right -= 1

n = int(input("Enter number of elements: ")) myList = [] for i in range(n): element = int(input("Enter element: ")) myList.append(element)

print("Original list:", myList) reverse_in_place(myList) print("Reversed list:", myList)

The program reads n elements from the user and stores them in a list. This list is passed to the function reverse_in_place(). Since lists are mutable, we can modify the contents directly. The function uses two pointers—left starting from the beginning and right from the end. Elements at these positions are swapped, and pointers move towards the centre until they meet. This reverses the list in-place without creating a new list.

Exercise: Programming Problems | Q: 9 | (Page 18)
For More Understanding

Explanation

The question requires an in-place reversal without creating a new list. The textbook context states that 'lists are mutable' meaning contents can be changed after creation. The solution uses the two-pointer swapping technique which modifies the original list directly. The function swaps elements from both ends moving towards the centre, achieving reversal in O(n/2) time complexity without using extra memory for a new list.

Solution Steps

  1. Step 1: Read n and create a list by appending n elements from user input

  2. Step 2: Define a function that takes a list as parameter

  3. Step 3: Initialize left=0 and right=len(lst)-1 as two pointers

  4. Step 4: Use while loop to swap elements at left and right positions until left >= right

  5. Step 5: Call the function with the list and display the reversed list