Sobes.tech
Junior — Middle

What methods in Python can be used to reverse the order of elements in a list?

sobes.tech AI

Answer from AI

In Python, there are several ways to reverse the order of list elements:

  1. The reverse() method — modifies the list in place:
lst = [1, 2, 3, 4]
lst.reverse()
print(lst)  # [4, 3, 2, 1]
  1. Slicing with a step of -1 — creates a new reversed list:
lst = [1, 2, 3, 4]
reversed_lst = lst[::-1]
print(reversed_lst)  # [4, 3, 2, 1]
  1. The reversed() function — returns an iterator, which can be converted into a list:
lst = [1, 2, 3, 4]
reversed_lst = list(reversed(lst))
print(reversed_lst)  # [4, 3, 2, 1]

The choice of method depends on whether you want to modify the original list or obtain a new one.