Reverse a List python
Sorting a List Permanently with the sort() Method
Python’s
sort()
method makes it relatively easy to sort a list. Imagine we have a list of student names and want to change the order of the list to store them alphabetically.
students = ['benny', 'alice', 'tony', 'sam'] students.sort() print(students)
The
sort()
method, changes the order of the list permanently. The students are now in alphabetical order, and we can never revert to the original order.
# ['alice', 'benny', 'sam', 'tony']
How to Reverse a List in Python
You can also sort this list in reverse alphabetical order by passing the argument
reverse=True
to the
sort()
method.
students = ['benny', 'alice', 'tony', 'sam'] students.sort(reverse=True) print(students)
Again, the order of the list is permanently changed
['tony', 'sam', 'benny', 'alice']
Sorting a List Temporarily with the sorted() Function
To maintain the original order of a list but present it in a sorted order, you can use the
sorted()
function. The
sorted()
function lets you display your list in a particular order but doesn’t affect the actual order of the list.
students = ['benny', 'alice', 'tony', 'sam'] print("Here is the original list:") print(students) print("\nHere is the sorted list:") print(sorted(students))
Here is the original list: ['benny', 'alice', 'tony', 'sam'] Here is the sorted list ['alice', 'benny', 'sam', 'tony']
Notice that the list still exists in its original order after the
sorted()
function has been used. The
sorted()
function can also accept a
reverse=True
argument if you want to display a list in reverse alphabetical order.
Printing a List in Reverse Order
To reverse the original order of a list, you can use the
reverse()
method.
students = ['benny', 'alice', 'tony', 'sam'] print(students) students.reverse() print(students)
The
reverse()
doesn’t sort backward alphabetically.It simply reverses the order of the list.
['benny', 'alice', 'tony', 'sam'] ['sam', 'tony', 'alice', 'benny']