In this code, two different options are shown to reverse the elements of a list.
The first option uses the reversed
function. The reversed
function returns an iterator that produces the items of the list in reverse order. The for
loop is used to loop through the reversed list and print each element.
The second option uses slicing. Slicing is a technique in Python that allows you to extract a portion of a list. The syntax list[start:stop:step]
is used to slice a list. If the start
and stop
indices are omitted, the default values are 0 and the length of the list, respectively. If the step
is negative, it causes the slice to include items from the list in reverse order. In this case, the slice list[::-1]
returns a new list that contains all items from the original list in reverse order.
list = [0, 4, 8, 12, 16]
# first option
for i in reversed(list):
print(i)
# second option
print(list[::-1])
16
12
8
4
0
[16, 12, 8, 4, 0]