In this article, you’ll learn how to sort a list with Python’s List sort() method.
The sort() method is used to sort a list:
list.sort()
The sort() method keeps the order of the original list. The sort() method changes the order of the elements in the list.
The less-than operator () is used by default in the sort() method to sort the members of a list. To put it another way, it prioritises the lower elements over the higher ones.
The reverse=True option to the sort() method is used to sort elements from higher to lower:
list.sort(reverse=True)
How to Sort List of Strings using Python List Sort method?
When a list contains strings, the sort() method alphabetizes the string elements.
The sort() method is used in the following example to order the elements in the guests list alphabetically:
guests = ['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer'] guests.sort() print(guests)
Output
[‘James’, ‘Jennifer’, ‘John’, ‘Mary’, ‘Patricia’, ‘Robert’]
The next example utilises the sort() method with the reverse=True option to reverse the alphabetical order of the elements in the guests list:
guests = ['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer'] guests.sort(reverse=True) print(guests)
Output
[‘Robert’, ‘Patricia’, ‘Mary’, ‘John’, ‘Jennifer’, ‘James’]
lambda expression
Python allows you to define a function without giving it a name using the following syntax:
lambda arguments: expression
An anonymous function is a function that has no name. A lambda expression is the name for this syntax.
It’s the technical equivalent of the following function:
def name(arguments): return expression
To sort the companies by revenue from low to high, use the lambda expression in the following example:
companies = [('Google', 2019, 134.81), ('Apple', 2019, 260.2), ('Facebook', 2019, 70.7)] # sort the companies by revenue companies.sort(key=lambda company: company[2]) # show the sorted companies print(companies)
Output
[('Apple', 2019, 260.2), ('Google', 2019, 134.81), ('Facebook', 2019, 70.7)]
Leave a Reply