Contents
Sorting a list in Python is a relatively simple process. In this article, we’ll show you how to sort a list in Python using the built-in sorted() function.
Checkout this video:
Python’s sorted() Function
The sorted() function returns a sorted list from the items in an iterable. You can specify ascending or descending order. The default is ascending order. The syntax of the sorted() function is:
sorted(iterable, key=None, reverse=False)
The sorted() function takes three arguments:
iterable – A sequence (string, tuple, list) or set to be sorted
key – Optional. A function that serves as a key for the sort comparison. Defaults to None
reverse – Optional. If True, the list is sorted in descending order. Defaults to False
The sort() Method
The sort() method sorts the elements of a given list in a specific order – Ascending or Descending.
The default order is Ascending. To sort the list in reverse order or Descending order, use the reverse parameter with a value of True.
You can also sort the list in Descending order by using the reverse parameter with a value of False.
The sorted() Function vs. The sort() Method
The sorted() function sorts the elements of a list in a specific order (either ascending or descending).
The sort() method sorts the elements of a list in a specific order (either ascending or descending).
The difference between the two is that the sorted() function returns a new list, while the sort() method sorts the list in place.
Here’s an example of each:
#sort a list of numbers in ascending order
numbers = [5, 2, 1, 3, 4]
sorted(numbers) # [1, 2, 3, 4, 5]
numbers.sort() # [1, 2, 3, 4, 5]
Sorting a List in Reverse Order
Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.
In this tutorial, we will learn how to sort a list in reverse order with three different methods.
With the reverse parameter, we can sort the list in reverse order:
“`
list.sort(reverse=True)
“`
The sorted() function also accepts the reverse argument:
“`
sorted(list, reverse=True)
“`
We can also use the Python built-in reversed() function to create a new reversed iterator and then pass it to the sorted() function.
“`
Sorting a List of Tuples
In Python, a tuple is a sequence of immutable objects. Unlike lists, tuples are unable to be sorted in place. However, it is possible to sort a list of tuples. The first element in each tuple is used as the key for comparison. This has the effect of sorting the list by the first item in each tuple. If the first items in each tuple are equal, then the second items are compared, and so on.
To sort a list of tuples by the first element in each tuple, we use the following syntax:
`list_of_tuples.sort(key=lambda x: x[0])`
Where `list_of_tuples` is the name of our list of tuples and `x[0]` indicates that we want to sort by the first element in each tuple.
Sorting a List of Dictionaries
Sorting a list of dictionaries by a specific key is a common operation in data science. For example, you might want to sort a list of employees by their hire date, or sort a list of blog posts by the date they were published.
Fortunately, Python makes it easy to sort a list of dictionaries by a specific key. The sorted() function takes two arguments: the list to be sorted and the key to sort by. To sort by multiple keys, pass in a list of keys as the second argument.
Here’s an example of how to sort a list of dictionaries by the “name” key:
employees = [
{‘name’: ‘John’, ‘hire_date’: ‘1/1/2010’},
{‘name’: ‘Jane’, ‘hire_date’: ’12/31/2009′},
{‘name’: ‘Bob’, ‘hire_date’: ‘4/15/2011’}
]
sorted_employees = sorted(employees, key=lambda x: x[‘name’])
print(sorted_employees)
##Output: [{‘hire_date’: ’12/31/2009′, ‘name’: ‘Jane’}, {‘hire_date’: ‘1/1/2010’, ‘name’: ‘John’}, {‘hire_date’: ‘4/15/2011’, , name=’Bob”}]
Sorting by Multiple Keys
To sort by multiple keys, you first need a function that takes multiple keys as arguments, and then pass this function as the key to the sorted() method. For example:
def by_last_name_first_name(student):
return (student[1], student[0])
students = [
(‘John’, ‘Smith’),
(‘Jane’, ‘Doe’),
(‘Joe’, ‘Bloggs’),
]
students.sort(key=by_last_name_first_name)
This will sort the list of students by last name, and if two students have the same last name, it will sort them by first name.
The itemgetter() Function
The itemgetter() function is a built-in function that can be used to sort a list. It takes as input a list and an integer, and returns the item at the given index in the list.
For example, if we have a list of integers:
>>> my_list = [3, 2, 1]
>>> sorted(my_list)
[1, 2, 3]
We can use the itemgetter() function to sort the list according to the values in the second position:
>>> from operator import itemgetter
>>> sorted(my_list, key=itemgetter(1))
[3, 2, 1]
We can also use negative indices with itemgetter(). If we use a negative index, the sorting will be done in reverse order:
The attrgetter() Function
Python lists have a built-in sorted() method that modifies the list in-place and a sorted() function that builds a new sorted list from an iterable.
There are a few ways to sort lists in Python. The simplest way is to use the built-in sorted() function, which takes a list and returns a new list with the same elements in sorted order.
We can also use the sort() method, which modifies the list in-place. The sorted() function is faster than sort() because it doesn’t have to create a new list.
The attrgetter() function is another way to sort lists. It takes one or more attribute names as arguments and returns a callable that can be used to fetch the named attributes from an object. The attrgetter() function is useful for sorting objects based on their attributes.
To sort a list of objects by an attribute, we first need to create an attrgetter() callable that will fetch the desired attribute from each object. We can then pass this callable to the sorted() function as the key argument.
Conclusion
In this article, we have learned how to sort a list in Python using three different methods. We have also learned about the time complexity of each method. I hope this article was helpful in understanding how to sort a list in Python.