The list reverse() method reverses the items of a list. Here's a quick example:
models = ['Claude', 'ChatGPT', 'Gemini']
models.reverse()
print(models)
Output
['Gemini', 'ChatGPT', 'Claude']
reverse() Syntax
The syntax of reverse() is:
my_list.reverse()
Arguments
reverse() doesn't take any arguments.
Return Value
reverse() doesn't return any value (returns None).
Example: Reverse a List
models = ['Claude', 'ChatGPT', 'Gemini']
print(f'Original List: {models}')
# Reverse list
models.reverse()
print('Reversed List:', models)
Output
Original List: ['Claude', 'ChatGPT', 'Gemini'] Reversed List: ['Gemini', 'ChatGPT', 'Claude']
It's important to remember that reverse() reverses the original list. Therefore, if you need the original list unmodified, copy it first using the copy() method.
Another way to reverse a list is by using slicing.
Example: Reverse a List Using Slicing
models = ['Claude', 'ChatGPT', 'Gemini']
reversed_models = models[::-1]
print(reversed_models)
Output
['Gemini', 'ChatGPT', 'Claude']
To learn more about how the above program works, visit Python slicing.
Example: Access Items in Reversed Order
If you need to access items of a list in reverse order (without modifying the original list), you can do it using the reversed() function.
models = ['Claude', 'ChatGPT', 'Gemini']
for model in reversed(models):
print(model)
Output
Gemini ChatGPT Claude
Also Read:
- Python sorted() Function - Sort items of any iterable and return a list.
- Python list sort() - Sort items of a list.