reverse a list in python

There are many ways to reverse a list in Python, but a simple and efficient way is using slicing method. Here is an example:

main.py
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)
77 chars
4 lines

Output: [5, 4, 3, 2, 1]

In this example, we use the slicing notation [::-1], which means starting from the end and taking each element till the beginning of the list with a step of -1. This returns a new list with the elements in reverse order.

Another way is to use the reverse() method, which modifies the original list in place:

main.py
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)
59 chars
4 lines

Output: [5, 4, 3, 2, 1]

Both methods can be useful depending on your specific use case.

gistlibby LogSnag