Slicing with the negative step, we get items in reverse format.
colors_list = ["Red", "Blue", "Green", "Orange"]
print(colors_list[::-1])
['Orange', 'Green', 'Blue', 'Red']
In the output, you can see that slicing with the negative step reverses all items.
A list of items can reverse using Python's inbuilt reverse()
function.
colors_list = ["Red", "Blue", "Green", "Orange"]
colors_list.reverse()
print(colors_list)
['Orange', 'Green', 'Blue', 'Red']
This output shows that all the list items reverse using the reverse()
function.
To reverse all items using logic, you must iterate the original list, pick items from the end and add them to the new temporary list.
colors_list = ["Red", "Blue", "Green", "Orange"]
new_colors_list = []
length = len(colors_list)
temp = length - 1
for i in range(length):
new_colors_list.append(colors_list[temp])
temp = temp - 1
print(new_colors_list)
['Orange', 'Green', 'Blue', 'Red']
In the output, you can see that all the list items reverse manually, using for loop iteration.