Q.Read a list of n elements. Pass this list to a function which reverses this list in-place without creating a new list.
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Swap the first element with the last, the second with the second-last, and so on up to the middle — the list is reversed inside the same object, with no new list created.
The idea (in-place reversal). Because a list is mutable and is passed to a function by reference, the function can rearrange the caller's own list. Reversal in place needs only pairwise swaps: for a list of n elements, swap index i with index n-1-i for i = 0, 1, …, n//2 - 1. We stop at the middle — going further would swap every pair back again.
Program
def reverse_in_place(lst):
n = len(lst)
for i in range(n // 2):
lst[i], lst[n - 1 - i] = lst[n - 1 - i], lst[i]
# ---- main program ----
n = int(input("How many elements? "))
lst = []
for i in range(n):
lst.append(int(input("Enter element " + str(i + 1) + ": ")))
print("Original list:", lst)
reverse_in_place(lst)
print("Reversed list:", lst)
Dry run for lst = [1, 2, 3, 4, 5] (n = 5, so the loop runs for i = 0, 1):
| Step | i | Swap performed | List after the swap |
|---|---|---|---|
| start | — | — | [1, 2, 3, 4, 5] |
| 1 | 0 | lst[0] and lst[4] (1 and 5) | [5, 2, 3, 4, 1] |
| 2 | 1 | lst[1] and lst[3] (2 and 4) | [5, 4, 3, 2, 1] |
The middle element (index 2) stays put for odd n.
Sample run (expected output)
How many elements? 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]
``` …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.