To reverse a list in Python, you can use one of these simple methods:
1. Using the reverse() method
Reverses the list in place (modifies the original list).
my_list = [1, 2, 3, 4, 5] my_list.reverse() print(my_list) # Output: [5, 4, 3, 2, 1]
2. Using slicing [::-1]
Creates a new reversed list (original list remains unchanged).
my_list = [1, 2, 3, 4, 5] reversed_list = my_list[::-1] print(reversed_list) # Output: [5, 4, 3, 2, 1]
3. Using the reversed() function
Returns a reverse iterator, which you can convert back to a list:
my_list = [1, 2, 3, 4, 5] reversed_list = list(reversed(my_list)) print(reversed_list) # Output: [5, 4, 3, 2, 1]
Key Differences
reverse()modifies the original list.[::-1]andreversed()create new reversed lists.Slicing (
[::-1]) is the most concise and commonly used method.
Choose the method based on whether you need to modify the original list or preserve it!
Comments
Post a Comment