How to make a list in the reverse order Python

"Reverse the order of a list in Python using slicing, reversed() or [::-1] with an example."

Reversing a List in Python

Reversing a list in Python is a common operation that can be done in a few different ways. The easiest way is to use the built-in reversed() function. This function takes an iterable object, such as a list, and returns a reversed iterator object. To get the reversed list, you need to convert it to a list.


# example list
my_list = [1,2,3,4,5,6,7]

# using the reversed() function
reversed_list = list(reversed(my_list)) 

# printing the reversed list
print(reversed_list)
# Output: [7, 6, 5, 4, 3, 2, 1]

Another way to reverse a list is to use slicing. Slicing is a powerful tool in Python that allows us to access a subset of a sequence. To reverse a list, we just need to create a slice that starts at the end of the list and ends at the beginning, with a step size of -1.


# example list
my_list = [1,2,3,4,5,6,7]

# using slicing
reversed_list = my_list[::-1] 

# printing the reversed list
print(reversed_list)
# Output: [7, 6, 5, 4, 3, 2, 1]

The last way to reverse a list is to use the reverse() method. This method modifies the original list in-place, so you don't need to assign the reversed list to a new variable. It is a more efficient solution than using the reversed() function or slicing, but it does alter the original list.


# example list
my_list = [1,2,3,4,5,6,7]

# using the reverse() method
my_list.reverse() 

# printing the reversed list
print(my_list)
# Output: [7, 6, 5, 4, 3, 2, 1]

These are the three ways you can reverse a list in Python. Using the built-in reversed() function is the easiest way, but it may not be the most efficient. If you need to reverse a list and modify the original list, then the reverse() method is the best option.

Answers (0)