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.py77 chars4 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.py59 chars4 lines
Output: [5, 4, 3, 2, 1]
Both methods can be useful depending on your specific use case.
gistlibby LogSnag