Every programmer has to write code that involves sorting data at some point. As you progress your Python skills, you may find yourself dealing with a sorting problem critical for user experience in an application.
You may need to write code to keep track of user activity by timestamp. You may also need to write a script that arranges email recipients in alphabetical order.
Python boasts built-in sorting functions that make it easy for programmers to sort different types of data. The language also includes features that enable programmers to customize the sorting operation at a granular level.
Here's a quick guide on how to sort a list in Python.
How To Sort A List In Python
Python has two built-in functions that can help you sort lists: sort() and sorted(). Both of the functions work with the same parameters. However, the two functions have different syntax and interact with iterables differently.
That being said, learning to use both functions makes sorting lists a breeze. If you're not familiar with creating a list in Python, going through our easy guide before reading on is a good idea.
Here's a detailed breakdown of how to use both sorting methods.
Sort Method
The Python list sort() method allows programmers to sort data in ascending and descending order. By default, the method will sort the list in ascending order.
Programmers can also write a function to customize the sorting criteria.
The syntax of the sort method is:
list.sort(reverse=True|False, key=myFunc)
Where "list" must be replaced with the variable's name that the data is stored in. The sort() function does not return any value. It sorts the values in the list directly, without making a new variable to store the sorted list in.
Here’s an example of how you can use the sort() function to sort data in ascending order:
names = ['Liam', 'Noah', 'Emma'] names.sort() print(names)
The output will be:
['Emma','Liam','Noah']
Parameters
The sort() function does not need any parameters to work. However, if you want to alter how the data is sorted, you can use the following parameters:
- key: It is a parameter that functions as a key for the sorting operation.
- reverse: If the parameter is set to "True," the list will sort in descending order.
Here’s an example of using the reverse parameter to sort a list in descending order:
names = ['Liam', 'Noah', 'Emma']
names.sort(reverse=True)
print(names)
The output of the code is:
['Noah', 'Liam', 'Emma']
You can sort lists according to length using the key parameter. Here's an example of a script that does this:
def myFunc(e): return len(e) names = ['Emily', 'Fred', 'Robert'] names.sort(key=myFunc) print(names)
The output of the script is:
['Fred', 'Emily', 'Robert']
Sorted Method
The other way of sorting a list in ascending or descending order in Python is by using the sorted() method. Like sort(), it does not have to be defined since it is a built-in function. Every standard version of Python comes with the method built-in.
Furthermore, it can be used without any parameters, similar to sort(). By default, the function arranges data in ascending order.
However, unlike sort(), the sorted() function stores the arranged values in a new list. The original list remains unaltered after the function is applied. In contrast, the sort() function returns “None.”
Consequently, the ordered list of data returned by the function can be assigned to a variable after the function is performed.
Objects in Python that you can iterate over are called iterables. The sorted() method works with all iterables. In other words, besides lists, sorted() will also work with strings, tuples, and sets.
The syntax of the method is:
sorted(iterable, key, reverse)
Another advantage of using sorted() is that you can pass the values to it without making a variable and storing values in it first.
For example:
sorted([10, 9, 8, 7, 6]) #result = [6,7,8,9,10]
That’s not to say that the sorted() function cannot work with variables:
>>> exampleList = [7, 9, 2, 4] >>> sorted(exampleList) [2, 4, 7, 9] >>> exampleList [7, 9, 2, 4] # Values of exampleList did not change. New list was returned.
Parameters
The sorted() method shares parameters with sort(). Using the "reverse" parameter will output a list in descending order, and you can define the sorting order using the "key" parameter.
Here’s an example of sorting in descending order with the sorted() method:
>>> names = ['Liam', 'Noah', 'Emma'] >>> sorted(names) ['Emma', 'Liam', 'Noah'] >>> sorted(names, reverse=True) ['Noah', 'Liam', 'Emma']
The sorting logic hasn't changed – the names are still being sorted by the first letter. However, the output has been reversed since the parameter is set to "True." If the parameter were set to "False," the result would remain unchanged.
The "key" argument is the most powerful component of the sorted() method. It expects a function to be passed, which is then used on each value in the list to derive the order of the data.
For instance, you can order a list of words according to their length using the key parameter:
>>> exampleWords = ['cat', 'mouse', 'chicken', 'bird'] >>> sorted(exampleWords, key=len) ['cat', 'bird', 'mouse', 'chicken']
To sort the list above in descending order of length, you could couple the key parameter with the reverse parameter.
>>> exampleWords = ['cat', 'mouse', 'chicken', 'bird'] >>> sorted(exampleWords, key=len, reverse=True) ['chicken', 'mouse', 'bird', 'cat']
Sometimes, instead of writing a standalone function for use with the key argument, you can use the lambda function, which is a built-in function.
The anonymous function has four characteristics:
- It must be defined inline;
- It cannot contain statements;
- It doesn't have a name; and
- It executes just like a function.
Let's say a programmer wants to write a program to sort a list of numbers according to their absolute value.
The script would look like this:
num_list = [1,-5,3,-9,25,10] def absolute_value(num): return abs(num) num_list.sort(key = absolute_value) print(num_list)
However, instead of writing the absolute_value function and assigning it to the key argument, we can use the following line:
num_list.sort(key = lambda num: abs(num))
Conclusion
Picking which method to use to sort a list can be confusing. Here's a good way to go about picking the method:
If you don't need the original list, using sort() is the right way to go. It doesn't make a new list, hence using less memory and increasing the code's efficiency.
However, if you think you'll need access to the original list at a later time, you must use the sorted() function.
Python can help you do a lot more than sort data. Reading our usage guide is a great way to get acquainted with all that Python can do.