logo
Python Data Structures - Interview Questions and Answers
How do you reverse a list in Python?
There are several ways to reverse a list in Python, each with its own nuances:

1. Using reversed() and list() :
* This method creates a reversed iterator and then converts it back into a list.
* It's efficient for iterating through the reversed list without modifying the original.
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)  # Output: [5, 4, 3, 2, 1]
print(my_list) #Output: [1, 2, 3, 4, 5]?

2. Using slicing :
* This is a concise and commonly used method.
* It creates a new reversed list without altering the original.
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)  # Output: [5, 4, 3, 2, 1]
print(my_list) #Output: [1, 2, 3, 4, 5]?

3. Using list.reverse() :
* This method reverses the list in-place, meaning it modifies the original list directly.
* It doesn't return a new list; it returns None.
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)  # Output: [5, 4, 3, 2, 1]?

Which method to choose :
* If you need a new reversed list without modifying the original, use reversed() with list() or slicing ([::-1]). Slicing is generally preferred for its brevity.
* If you want to reverse the list in-place and don't need the original order, use list.reverse().