To reverse a list in-place, that is, without creating a new list, use the builtin reverse()
method from list
:
car_brands = ["bmw", "ferrari", "mclaren"]
print(car_brands)
car_brands.reverse()
print(car_brands)
['bmw', 'ferrari', 'mclaren']
['mclaren', 'ferrari', 'bmw']
To keep the original list and assign the reversed list to a new one, use the slice syntax:
car_brands = ["bmw", "ferrari", "mclaren"]
car_brands_reversed = car_brands[::-1]
print(car_brands)
print(car_brands_reversed)
['bmw', 'ferrari', 'mclaren']
['mclaren', 'ferrari', 'bmw']
The slice syntax allows you to set a step, which is -1
in the example.
The default step is 1
, that is, go forward 1 item of the list at a time.
If you set the step to -1
you have the opposite, go back 1 item at a time.
So you start at the position of the last item and move backwards to the first item at position 0.
To learn more about slicing, check out Understanding Slicing in Python.