In this Python article, we will take a deep dive into the Python List sort() method – a powerful and handy technique for sorting the elements of a Python list.
We will cover its syntax, usage, and explore some examples to better understand its practical applications.
List sort() method in Python
Below are the topics that we are doing to discuss in this article:
- Introduction to Python List sort() method
- Syntax of the sort() method
- Purpose and use cases of the sort() method
Python List sort() method
The list sort() method in Python is a built-in method that allows you to sort a list of items in ascending or descending order, depending on the specified parameters.
The method operates in-place, which means that the original Python list is modified instead of returning a new, sorted Python list.
Syntax:
The syntax for the list sort() method is as follows:
list.sort(key=None, reverse=False)
Parameters:
The list sort() method accepts two optional parameters:
key
: A function that serves as a custom sorting criteria. This function takes an item as input and returns a value used for sorting. By default, thekey
parameter is set to None, which means that the items will be sorted based on their natural ordering.reverse
: A boolean value that, if set to True, sorts the list in descending order. By default, thereverse
parameter is set to False, which means that the list will be sorted in ascending order.
sort() method in Python List Examples
Let’s explore a few examples to illustrate the usage of the list sort() method.
Example#1 Sorting a list of numbers in ascending order
temperatures = [68, 32, 55, 79, 42]
temperatures.sort()
print(temperatures)
The Python list of temperatures (in Fahrenheit) recorded in different cities is sorted in ascending order using the sort() method. The result is a Python list of temperatures ordered from the lowest to the highest.
Output:
Example#2 Sorting a list of strings in descending order
states = ['Texas', 'California', 'New York', 'Florida', 'Washington']
states.sort(reverse=True)
print(states)
The Python list of US states is sorted in descending alphabetical order using the sort() method with the reverse
parameter set to True. The result is a Python list of states ordered from Z to A.
Output:
Example#3 Sorting a list of dictionaries based on a specific key
cities = [
{'name': 'Los Angeles', 'population': 3898747},
{'name': 'New York', 'population': 8336817},
{'name': 'Chicago', 'population': 2693976},
]
cities.sort(key=lambda x: x['population'])
print(cities)
The Python list of US cities, represented as dictionaries with their respective populations, is sorted in ascending order based on their populations. The Python sort() method uses a lambda function as the key
parameter to extract the population value from each dictionary.
Output:
Example#4 Sorting a list of tuples based on the second element
landmarks = [
(37.7749, -122.4194), # San Francisco
(40.7128, -74.0060), # New York City
(34.0522, -118.2437), # Los Angeles
(41.8781, -87.6298), # Chicago
(47.6062, -122.3321), # Seattle
]
landmarks.sort(key=lambda x: x[0]) # Sorting by latitude
print(landmarks)
The Python list of GPS coordinates representing the latitude and longitude of famous US landmarks is sorted in ascending order based on latitude. The Python sort() method uses a lambda function as the key
parameter to extract the latitude value (the first element) from each tuple.
The result is a Python list of landmarks ordered from the southernmost to the northernmost.
Output:
Example#5 Sorting a list of movie titles in alphabetical order
movies = ['The Godfather', 'Pulp Fiction', 'Forrest Gump', 'The Shawshank Redemption', 'Inception']
movies.sort()
print(movies)
The Python list of movie titles is sorted in alphabetical order using the sort() method. The result is a Python list of movies ordered from A to Z.
Output:
Conclusion
The Python list sort() method provides a powerful and flexible way to order the elements of a list based on their natural ordering or custom sorting criteria. The method offers optional parameters, such as key
and reverse
, to help us customize the sorting process according to our needs.
You may also like to read the following articles:
- Python List pop() method [With Examples]
- How to Python Append List to Another List
- How to Sum Elements in List in Python using For Loop
- How to get string values from list in Python
- Python list len() method [With Examples]
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.