How to reverse a list in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To reverse a list in Python, you can use the reverse() method, which modifies the original list in place by reversing the order of its elements. Here’s an example:

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)

Output:

[5, 4, 3, 2, 1]

In this example, we define a list of numbers and then use the reverse() method to reverse the order of the elements in the list. The resulting list is [5, 4, 3, 2, 1].

Alternatively, you can use the built-in reversed() function to obtain a reversed view of the list, which can be converted to a new list using the list() constructor. Here’s an example:

my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)

Output:

[5, 4, 3, 2, 1]

In this example, we define a list of numbers and then use the reversed() function to obtain a reversed view of the list. We then convert the reversed view to a new list using the list() constructor. The resulting list is [5, 4, 3, 2, 1].

I hope this helps! Let me know if you have any other questions.

Tags: