Sobes.tech
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:

  1. Using slicing with a step of -1:

    my_list = [1, 2, 3, 4, 5]
    reversed_list = my_list[::-1] # Creates a new reversed list
    
  2. 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.

  3. Using the reverse() method:

    my_list = [1, 2, 3, 4, 5]
    my_list.reverse() # Reverses the list "in place", mutating the original list
    

    This 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.