English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The reverse() method reverses the elements in the given list. That is, it sorts the elements in the list in reverse order
The syntax of the reverse() method is:
list.reverse()
reverse() function does not accept any parameters.
The reverse() function does not return any value. It only reverses the arrangement of elements and updatesList.
# List of operating systems os = ['Windows', 'macOS', 'Linux'] print('Original list:', os) # List reversal os.reverse() # Update list print('Updated list:', os)
When running the program, the output is:
Original list: ['Windows', 'macOS', 'Linux'] Updated list: ['Linux', 'macOS', 'Windows']
There are several other methods to reverse a list.
# List of operating systems os = ['Windows', 'macOS', 'Linux'] print('Original list:', os) # Reverse the list # Syntax: reversed_list = os[start:stop:step] reversed_list = os[::-1] # Updated list print('Updated list:', reversed_list)
When running the program, the output is:
Original list: ['Windows', 'macOS', 'Linux'] Updated list: ['Linux', 'macOS', 'Windows']
If you need to access each element of the list in reverse order, it is best to use the reversed() method.
# List of operating systems os = ['Windows', 'macOS', 'Linux'] # Print elements in reverse order for o in reversed(os): print(o)
When running the program, the output is:
Linux macOS Windows