Sorted
The Python built-in sorted()
We’ve seen that lists are mutable, and that a list can be sorted in-place with the list method .sort()
. Example:
>>> hand = ['8♥︎', '5♦︎', '2♣︎', '9♠︎', '4♥︎']
>>> hand.sort() # notice there's no assignment!
>>> hand
['2♣︎', '4♥︎', '5♦︎', '8♥︎', '9♠︎']
However, because strings and tuples are immutable, they have no .sort()
method.
>>> ("Dolores", "Bob", "Egbert", "Alice", "Charlene").sort()
Traceback (most recent call last):
File "<python-input-12>", line 1, in <module>
("Dolores", "Bob", "Egbert", "Alice", "Charlene").sort()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'sort'
>>> 'fhtasunbweycjqzplivokgxmdr'.sort()
Traceback (most recent call last):
File "<python-input-25>", line 1, in <module>
'fhtasunbweycjqzplivokgxmdr'.sort()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'sort'
But sometimes we want to sort a string or tuple. Does this mean we’re out of luck? No. Python provides a built-in for this: sorted()
.
sorted()
takes an iterable as an argument and returns a sorted list of the elements in the iterable. Examples:
>>> sorted('fhtasunbweycjqzplivokgxmdr')
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z']
>>> sorted(("Dolores", "Bob", "Egbert", "Alice", "Charlene"))
['Alice', 'Bob', 'Charlene', 'Dolores', 'Egbert']
Now, you may say “That’s fine, but what if I want a sorted string or tuple and not a list?” Easy. Just construct the desired object from the sorted list. For a string we can use join()
:
>>> "".join(sorted('fhtasunbweycjqzplivokgxmdr'))
'abcdefghijklmnopqrstuvwxyz'
For a tuple, we just use the tuple constructor:
>>> tuple(sorted(("Dolores", "Bob", "Egbert",
... "Alice", "Charlene")))
('Alice', 'Bob', 'Charlene', 'Dolores', 'Egbert')
Comprehension check
Why don’t objects of type
str
ortuple
have a.sort()
method?What’s the result of
tuple(sorted('egbert'))
?What’s the result of
"".join(sorted('egbert'))
?Why won’t this work:
"".join(['c', 'b', 'a'].sort())
?How would you fix the example in #4 above?
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.