How to sort list in python
How to sort list in python
How to Sort a List in Python
Sorting a list is pretty easy: Python has built-in support for sorting lists.
Start with some data: Create a list of numbers and then call the sort() method. This method is directly called on the list object. This will work with any list, including list of pairs.
Sort example
Sort list
We define a list (x) with a bunch of numbers. Then call the sort method on the list object. We do not need to save the return variable, simply calling the method is enough.
Save the program (sort1.py) and run it. This will output all numbers in low to high order.
Do you have a list of strings? Strings can also be sorted.
Reverse order
To sort in reverse order, combine it with the method reverse()
All of the numbers will be shown in reverse order.
So what’s happening here?
First the list is sorted with x.sort().
Then it’s given to the function reversed() which takes a list as parameter. But, the function does not return a list object but an iterator. The method list() converts the output of reversed() and converts it to a list object.
Best way to sort in reverse order
You can sort the list in a more elegant way:
What’s this trickery?
Exercise
Given a list with pairs, sort on the first element
Sorting HOW TOВ¶
Andrew Dalke and Raymond Hettinger
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 document, we explore the various techniques for sorting data using Python.
Sorting BasicsВ¶
A simple ascending sort is very easy: just call the sorted() function. It returns a new sorted list:
Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.
Key FunctionsВ¶
Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.
For example, here’s a case-insensitive string comparison:
The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
A common pattern is to sort complex objects using some of the object’s indices as keys. For example:
The same technique works for objects with named attributes. For example:
Operator Module FunctionsВ¶
Using those functions, the above examples become simpler and faster:
The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:
Ascending and DescendingВ¶
Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is used to flag descending sorts. For example, to get the student data in reverse age order:
Sort Stability and Complex SortsВ¶
Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.
This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade:
This can be abstracted out into a wrapper function that can take a list and tuples of field and order to sort them on multiple passes.
The Timsort algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset.
The Old Way Using Decorate-Sort-UndecorateВ¶
This idiom is called Decorate-Sort-Undecorate after its three steps:
First, the initial list is decorated with new values that control the sort order.
Second, the decorated list is sorted.
Finally, the decorations are removed, creating a list that contains only the initial values in the new order.
For example, to sort the student data by grade using the DSU approach:
This idiom works because tuples are compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on.
It is not strictly necessary in all cases to include the index i in the decorated list, but including it gives two benefits:
The sort is stable – if two items have the same key, their order will be preserved in the sorted list.
The original items do not have to be comparable because the ordering of the decorated tuples will be determined by at most the first two items. So for example the original list could contain complex numbers which cannot be sorted directly.
Another name for this idiom is Schwartzian transform, after Randal L. Schwartz, who popularized it among Perl programmers.
Now that Python sorting provides key-functions, this technique is not often needed.
The Old Way Using the cmp ParameterВ¶
Many constructs given in this HOWTO assume Python 2.4 or later. Before that, there was no sorted() builtin and list.sort() took no keyword arguments. Instead, all of the Py2.x versions supported a cmp parameter to handle user specified comparison functions.
In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__() magic method).
In Py2.x, sort allowed an optional function which can be called for doing the comparisons. That function should take two arguments to be compared and then return a negative value for less-than, return zero if they are equal, or return a positive value for greater-than. For example, we can do:
Or you can reverse the order of comparison with:
When porting code from Python 2.x to 3.x, the situation can arise when you have the user supplying a comparison function and you need to convert that to a key function. The following wrapper makes that easy to do:
To convert to a key function, just wrap the old comparison function:
In Python 3.2, the functools.cmp_to_key() function was added to the functools module in the standard library.
Odd and EndsВ¶
For locale aware sorting, use locale.strxfrm() for a key function or locale.strcoll() for a comparison function.
The reverse parameter still maintains sort stability (so that records with equal keys retain the original order). Interestingly, that effect can be simulated without the parameter by using the builtin reversed() function twice:
The sort routines use when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an __lt__() method:
However, note that can fall back to using __gt__() if __lt__() is not implemented (see object.__lt__() ).
Key functions need not depend directly on the objects being sorted. A key function can also access external resources. For instance, if the student grades are stored in a dictionary, they can be used to sort a separate list of student names:
Python Sorting
The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed.
It’s most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection. The older list.sort() method is an alternative detailed below. The sorted() function seems easier to use compared to sort(), so I recommend using sorted().
The sorted() function can be customized through optional arguments. The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), makes it sort backwards.
Custom Sorting With key=
For more complex custom sorting, sorted() takes an optional «key=» specifying a «key» function that transforms each element before comparison. The key function takes in 1 value and returns 1 value, and the returned «proxy» value is used for the comparisons within the sort.
For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest. The sort calls len() for each string to get the list of proxy length values, and then sorts with those proxy values.
As another example, specifying «str.lower» as the key function is a way to force the sorting to treat uppercase and lowercase the same:
You can also pass in your own MyFn as the key function, like this:
For more complex sorting like sorting by last name then by first name, you can use the itemgetter or attrgetter functions like:
sort() method
As an alternative to sorted(), the sort() method on a list sorts that list into ascending order, e.g. list.sort(). The sort() method changes the underlying list and returns None, so use it like this:
Tuples
To create a size-1 tuple, the lone element must be followed by a comma.
It’s a funny case in the syntax, but the comma is necessary to distinguish the tuple from the ordinary case of putting an expression in parentheses. In some cases you can omit the parenthesis and Python will see from the commas that you intend a tuple.
Assigning a tuple to an identically sized tuple of variable names assigns all the corresponding values. If the tuples are not the same size, it throws an error. This feature works for lists too.
List Comprehensions (optional)
List comprehensions are a more advanced feature which is nice for some cases but is not needed for the exercises and is not something you need to learn at first (i.e. you can skip this section). A list comprehension is a compact way to write an expression that expands to a whole list. Suppose we have a list nums [1, 2, 3, 4], here is the list comprehension to compute a list of their squares [1, 4, 9, 16]:
You can add an if test to the right of the for-loop to narrow the result. The if test is evaluated for each element, including only the elements where the test is true.
Exercise: list1.py
To practice the material in this section, try later problems in list1.py that use sorting and tuples (in the Basic Exercises).
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
In this article, you will learn how to use Python’s sort() list method.
By the end, you will know the basics of sorting a list in Python and know how to customize the sorting to fit your needs.
Here is what we will cover:
The sort() method is one of the ways you can sort a list in Python.
The general syntax for the sort() method looks like this:
Let’s break it down:
How to Sort List Items in Ascending Order Using the sort() Method
As mentioned earlier, by default, sort() sorts list items in ascending order.
Ascending (or increasing) order means that items are arranged from lowest to highest value.
The lowest value is on the left hand side and the highest value is on the right.
The general syntax to do this would look something similar to the following:
Let’s take a look at the following example which shows how to sort a list of whole numbers:
In the example above, numbers are sorted from smallest to largest.
You can also achieve the same when working with a list of strings:
In this case, each string contained in the list was sorted in aplhabetical order.
As you saw in both examples, the original lists were directly changed.
How to Sort List Items in Descending Order Using the sort() Method
The general syntax to do this would look something like this:
Let’s reuse the same example from the previous section, but this time make it so the numbers are sorted in reverse order:
Now all the numbers are arranged in reverse, with the largest value being on the left hand side and the smallest on the right.
You can also achieve the same when working with a list of strings.
List items are now arranged in reverse alphabetical order.
How to Sort List Items Using the key parameter with the sort() Method
You can use the key parameter to perform more customized sorting operations.
The value assigned to the key parameter needs to be something callable.
Callable is something that can be called, which means it can be invoked and referenced.
Some examples of callable objects are methods and functions.
This method or function assigned to key will be applied to all the elements in the list before any sorting occurs and will specify the logic for the sorting criteria.
Say you want to sort a list of strings based on their length.
For that, you assign the built-in len() function to the key parameter.
The len() function will count the length of each element stored in the list by counting the characters contained in that element.
In the example above, strings are sorted in the default ascending order, but this time the sorting occurs based on their length.
The shortest string is on the left hand side and the longest on the right.
The key and reverse parameters can also be combined.
For example, you could sort the list items based on their length but in descending order.
In the example above, strings go from longest to shortest.
Another thing to note is that you can create a custom sorting function of your own, to create more explicit sorting criteria.
For example, you can create a specific function and then sort the list according to the return value of that function.
Say you have a list of dictionaries with programming languages and the year each programming language was created.
You can define a custom function that gets the value of a specific key from the dictionary.
💡 Keep in mind that a dictionary key and the key parameter that sort() accepts are two different things!
Specifically, the function will get and return the value of the year key in the list of dictionaries, which specifies the year when every language in the dictionary was created.
The return value will then apply as the sorting criteria for the list.
You can then sort according to the return value of the function you created earlier by assigning it to the key parameter and sort by the default ascending chronological order:
If you want to sort from the most recently created language to the oldest, or otherwise in descending order, you then use the reverse=True parameter:
To achieve exactly the same result you can create a lambda function.
Instead of using the regular custom function you defined using the def keyword, you can:
The lambda function which is specified with the line key=lambda element: element[‘year’] sorts these programming languages from oldest to most recent.
The Differences between sort() and sorted()
The sort() method works in a similar way to the sorted() function.
The general syntax of the sorted() function looks like this:
Let’s break it down:
The main difference between sort() and sorted() is that the sorted() function takes a list and returns a new sorted copy of it.
The new copy contains the elements of the original list in a sorted order.
The elements in the original list are not affected and remain unchanged.
So, to summarize the differences:
Let’s take a look at the following example to see how it works:
And when printing the original list you see that it has remained the same and the items have their original order.
Check out the following example to see what would happen if that was attemped with the sort() method.
Lastly, another thing to note is that the reverse and key parameters that the sorted() function accepts work the exact same way they do with the sort() method you saw in the previous sections.
When to Use sort() and sorted()
First, consider the type of data you’re working with:
Next, another thing to consider is whether it is important that you retain the original order of the list you’re working with:
Lastly, another thing you might want to consider when working with larger data sets, is time and memory efficiency:
Conclusion
And there you have it! You now know how to sort a list in Python using the sort() method.
I hope you found this article useful.
To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.
You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.
Sorting Mini-HOW TO
Original version by Andrew Dalke with a major update by Raymond Hettinger
Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable.
There are many ways to use them to sort data and there doesn’t appear to be a single, central place in the various manuals describing them, so I’ll do so here.
Sorting Basics
Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.
Key Functions
Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.
For example, here’s a case-insensitive string comparison:
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
A common pattern is to sort complex objects using some of the object’s indices as a key. For example:
The same technique works for objects with named attributes. For example:
Operator Module Functions
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter, attrgetter, and starting in Python 2.6 a methodcaller function.
Using those functions, the above examples become simpler and faster.
The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:
The third function from the operator module, methodcaller is used in the following example in which the weighted grade of each student is shown before sorting on it:
Ascending and Descending
Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is using to flag descending sorts. For example, to get the student data in reverse age order:
Sort Stability and Complex Sorts
Starting with Python 2.2, sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.
Notice how the two records for 'blue' retain their original order so that ('blue', 1) is guaranteed to precede ('blue', 2).
This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade:
The Timsort algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset.
The Old Way Using Decorate-Sort-Undecorate
For example, to sort the student data by grade using the DSU approach:
This idiom works because tuples are compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on.
The original items do not have to be comparable because the ordering of the decorated tuples will be determined by at most the first two items. So for example the original list could contain complex numbers which cannot be sorted directly.
Another name for this idiom is Schwartzian transform, after Randal L. Schwartz, who popularized it among Perl programmers.
For large lists and lists where the comparison information is expensive to calculate, and Python versions before 2.4, DSU is likely to be the fastest way to sort the list. For 2.4 and later, key functions provide the same functionality.
The Old Way Using the cmp Parameter
Many constructs given in this HOWTO assume Python 2.4 or later. Before that, there was no sorted() builtin and list.sort() took no keyword arguments. Instead, all of the Py2.x versions supported a cmp parameter to handle user specified comparison functions.
In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods).
In Py2.x, sort allowed an optional function which can be called for doing the comparisons. That function should take two arguments to be compared and then return a negative value for less-than, return zero if they are equal, or return a positive value for greater-than. For example, we can do:
Or you can reverse the order of comparison with:
When porting code from Python 2.x to 3.x, the situation can arise when you have the user supplying a comparison function and you need to convert that to a key function. The following wrapper makes that easy to do:
To convert to a key function, just wrap the old comparison function:
In Python 2.7, the cmp_to_key() tool was added to the functools module.
Maintaining Sort Order
Python does not provide modules like C++’s set and map data types as part of its standard library. This is a concious decision on the part of Guido, et al to preserve «one obvious way to do it.» Instead Python delegates this task to third-party libraries that are available on the Python Package Index. These libraries use various techniques to maintain list, dict, and set types in sorted order. Maintaining order using a specialized data structure can avoid very slow behavior (quadratic run-time) in the naive approach of editing and constantly re-sorting. Several implementations are described here.
Odd and Ends
For locale aware sorting, use locale.strxfrm() for a key function or locale.strcoll() for a comparison function.
HowTo/Sorting (last edited 2014-10-12 06:26:39 by Paddy3118 )