Python Code Example: list in reverse order

The following python code example outputs an array in reverse order.

Code Explanation

LineDescription
1Declaration and initialization of the list called list with the values 0, 4, 8, 12, 16
3 + 4The reversed() function is used to reverse a list.
7This is a slice function that reverses the list. It starts at the end of the list and takes each element. So it inverts a list.
list = [0, 4, 8, 12, 16]
# first option
for i in reversed(list):
    print(i)

# second option
print(list[::-1])
Output
16
12
8
4
0
[16, 12, 8, 4, 0]