Sign in to your Python Morsels account to save your screencast settings.
Don't have an account yet? Sign up here.
How can you sort things in Python?
sort
methodPython's lists have a sort
method, which will modify the list to order all of its items from smallest to largest:
>>> numbers = [4, 2, 7, 1, 5]
>>> numbers.sort()
>>> numbers
[1, 2, 4, 5, 7]
The sort
method relies on the less-than (<
) operator.
>>> "apple" < "banana"
True
So any object that works with the less-than operator can be sorted:
>>> fruits = ["apple", "kumquat", "banana", "blueberry", "kiwi"]
>>> fruits.sort()
>>> fruits
['apple', 'banana', 'blueberry', 'kiwi', 'kumquat']
But the sort
method modifies lists in place, instead of returning a new list.
And it only works on lists, because it's a method that lives on the list
class.
sorted
functionPython's built-in sorted
function is a more generic version of the list.sort
method.
>>> numbers = [4, 2, 7, 1, 5]
>>> sorted_numbers = sorted(numbers)
>>> sorted_numbers
[1, 2, 4, 5, 7]
The sorted
function works on any iterable, so we could sort a generator object:
>>> squares = (n*n for n in numbers)
>>> sorted(squares)
[1, 4, 16, 25, 49]
Or we could even sort lines in a file:
>>> with open("my_file.txt", mode="rt") as my_file:
... sorted(my_file)
...
['And this is the last line.\n', 'I quite like this file\n', 'This is my file!\n']
And since sorted
doesn't modify the passed-in iterable, if you just need to sort for the sole purpose of looping one time, you could call sorted
and then immediately loop over the result:
>>> numbers = [4, 2, 7, 1, 5]
>>> for n in sorted(numbers):
... print(n)
...
1
2
4
5
7
This use of sorted
makes it feel a little bit more like a looping helper, like the built-in enumerate
, reversed
, and zip
functions.
What if you want to sort from biggest to smallest?
The sorted
function accepts an optional reverse
argument.
When it's True
, it'll sort in descending order:
>>> numbers = [4, 2, 7, 1, 5]
>>> sorted(numbers, reverse=True)
[7, 5, 4, 2, 1]
In fact, the list.sort
method also accepts that reverse
argument.
If you give it a True
or truthy value, it sorts in descending order as well.
What if you wanted to sort by something that wasn't quite the original item?
For example, let's say we'd like to sort a list of strings, but not by the characters in the string. Instead, we'd like to sort them by their length.
Well, the sorted
function accepts an optional key
argument.
That key
argument should be a callable (i.e. something like a function).
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
Sorted will call that key function on each item in the given iterable, and it'll sort the items by the result of whatever that key function returns for each item.
So if we passed in the built-in len
function as our key function, sorted
will call len
on each item, and then it'll use that value (the length of each string) as the key to sort by:
>>> sorted(fruits, key=len)
['kiwi', 'apple', 'banana', 'kumquat', 'blueberry']
So you can see we're sorting these strings in order of their length, in ascending order.
sorted
to sort any iterableYou can use the built-in sorted
function to sort any iterable in Python.
We don't learn by reading or watching. We learn by doing. That means writing Python code.
Practice this topic by working on these related Python exercises.
Need to fill-in gaps in your Python skills?
Sign up for my Python newsletter where I share one of my favorite Python tips every week.
Unlike, JavaScript, C, Java, and many other programming languages we don't have traditional C-style for
loops.
Our for
loops in Python don't have indexes.
This small distinction makes for some big differences in the way we loop in Python.
To track your progress on this Python Morsels topic trail, sign in or sign up.
Sign in to your Python Morsels account to track your progress.
Don't have an account yet? Sign up here.