Intern
214
How to reverse a list in Python?
Answer from AI
sobes.tech AI
There are several ways to reverse a list in Python:
-
Using slicing with a step of -1:
my_list = [1, 2, 3, 4, 5] reversed_list = my_list[::-1] # Creates a new reversed list -
Using the
reversed()function:my_list = [1, 2, 3, 4, 5] # reversed() returns an iterator, which can be converted back to a list reversed_list = list(reversed(my_list))reversed()is a generator, more efficient for large lists if you don't need to create a new list immediately. -
Using the
reverse()method:my_list = [1, 2, 3, 4, 5] my_list.reverse() # Reverses the list "in place", mutating the original listThis method modifies the original list and does not return a new list.
The choice of method depends on whether you need a new reversed list or just want to modify the existing one, as well as performance considerations for very large lists. Slicing [::-1] and list(reversed(my_list)) create new lists, while my_list.reverse() modifies the original.