Introduction
Sorting a list means arranging all the elements in a certain order. The order may be the ascending or descending order. In this tutorial, you'll learn how to sort a list in python. There are two methods to do so, sort() and sorted() methods. We'll try both of them here.
sort() vs sorted() method in python
Both are used for sorting list elements. The main difference is sorted() method only shows the sorted value of a list. It doesn't change the order of the main data, but the sort() method sorts the list values permanently. Let's see an example.
sorted() method
languages = ['Python', 'C++', 'Java', 'Ruby', 'C#', 'PHP', 'HTML']
print("The main data:\n",languages)
# Sorting the list using the sorted() method
print("\nData in ascending order:\n", sorted(languages))
# Sorting in Descending order using the sorted method
print("\nData in descending order:\n", sorted(languages, reverse=True))
# Checking the list if it has been sorted or not
print("\nNow the list is:\n", languages)
Output
The main data:
['Python', 'C++', 'Java', 'Ruby', 'C#', 'PHP', 'HTML']
Data in ascending order:
['C#', 'C++', 'HTML', 'Java', 'PHP', 'Python', 'Ruby']
Data in descending order:
['Ruby', 'Python', 'PHP', 'Java', 'HTML', 'C++', 'C#']
Now the list is:
['Python', 'C++', 'Java', 'Ruby', 'C#', 'PHP', 'HTML']
As you can see, the sorted() method only shows the values in a sorted manner without modifying the original data. But the sort() method does change. The next example will help you a lot to understand it.
sort() method
lang = ['Python', 'C++', 'Java', 'Ruby', 'C#', 'PHP', 'HTML']
print("The List is:\n",lang)
# Sorting the list using the sort() method
lang.sort()
# Sorting in ascending order
print("\nData in ascending order:\n",lang)
# Sorting in Descending order using the sort() method
lang.sort(reverse=True)
print("\nData in descending order:\n",lang)
Output
The List is:
['Python', 'C++', 'Java', 'Ruby', 'C#', 'PHP', 'HTML']
Data in ascending order:
['C#', 'C++', 'HTML', 'Java', 'PHP', 'Python', 'Ruby']
Data in descending order:
['Ruby', 'Python', 'PHP', 'Java', 'HTML', 'C++', 'C#']
I hope you now understand the difference between sort() and sorted() methods and which one to use where.