How to reverse a list in Python?
You can reverse the order of elements in a list in Python using the reverse()
method or by using slicing.
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# Reversing the list using the reverse() method
numbers.reverse()
# Reversing the list using slicing
new_numbers = numbers[::-1]
Syntax
list.reverse()
Example using reverse () method
How to reverse a list in Python
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# Reversing the list using the reverse() method
numbers.reverse()
print("Reversed list:", numbers)
#output: Reversed list: [5, 4, 3, 2, 1]
Syntax for slicing
reversed_list = list_name[::-1]
Example using slicing
How to reverse a list in Python
# Creating a list of colors
colors = ['red', 'green', 'blue', 'yellow']
# Reversing the list using slicing
reversed_colors = colors[::-1]
print("Reversed list:", reversed_colors)
#output: Reversed list: ['yellow', 'blue', 'green', 'red']