Read a list of n elements. Pass this list to a function which reverses this list in-place without creating a new list.
Question
Read a list of $\mathrm{n}$ elements. Pass this list to a function which reverses this list in-place without creating a new list.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here is a program that reads a list of ( n ) elements and passes it to a function that reverses the list in place without creating a new list:
# Function to reverse the list in place
def reverse_list_in_place(lst):
left = 0
right = len(lst) - 1
while left < right:
# Swap the elements at positions left and right
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
# Read the number of elements
n = int(input("Enter the number of elements in the list: "))
# Read the list elements
lst = []
for i in range(n):
element = int(input(f"Enter element {i+1}: "))
lst.append(element)
print("Original list:", lst)
# Reverse the list in place
reverse_list_in_place(lst)
print("Reversed list:", lst)
Explanation
Function
reverse_list_in_place(lst)
:It takes a list
lst
.Two pointers
left
andright
are initialized to the start and end of the list.Elements are swapped while
left
is less thanright
, and pointers are moved closer to each other.
Reading input:
The user is prompted to enter the number of elements (
n
).A loop is used to read
n
elements from the user and append them to the listlst
.
Displaying results:
The original list is displayed.
The list is passed to
reverse_list_in_place(lst)
to reverse it.The reversed list is displayed.
This ensures that the list is reversed in-place without creating a new list.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month