๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_func_sorted.asp
Python sorted() Function
To sort a list by length, we can use the built-in len function.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ howto โ€บ sorting.html
Sorting Techniques โ€” Python 3.14.4 documentation
February 23, 2026 - Author, 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 lis...
Discussions

Sorting lists in python: sorted() vs sort()
sorted() is functional and .sort() is an instance method. Functions should preferably not modify input parameters while object method would be expected to modify act on the instance. Edit: I know that my statement doesn't hold true in all instances, but when making your own functions and methods it's a good way to implement it like described. Documentation is key as always. More on reddit.com
๐ŸŒ r/Python
32
904
May 16, 2022
sorting - How does the key argument in python's sorted function work? - Stack Overflow
The x[0] is not ignored; it's used to break ties with the first item in the tuple. That's why ('Baker', 20) will always come before ('Charlie', 20) ... When sorting tuples, Python first sorts by the first value. Then, if there are any ties (i.e. two or more tuples have the same first value), ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Sorting a set of values - Stack Overflow
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after). The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function: More on stackoverflow.com
๐ŸŒ stackoverflow.com
Tip - Use Python Builtin Binary Search (Bisect) on Sorted List
The example of using bisect to look up a range, given a specific value is : https://docs.python.org/3.11/library/bisect.html#examples More on reddit.com
๐ŸŒ r/pythontips
4
28
February 5, 2023
๐ŸŒ
Real Python
realpython.com โ€บ python-sort
How to Use sorted() and .sort() in Python โ€“ Real Python
February 24, 2025 - Just like before, you can use sorted() to iterate through each element of the iterable you pass in. In a string, each element means each character, including spaces. Note: Python sorts strings lexicographically by comparing Unicode code points ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-sorted-function
Python sorted() Function - GeeksforGeeks
December 20, 2025 - You can sort the elements of a tuple using sorted(), which returns a list. ... Explanation: Tuples are immutable, so sorted() returns a new sorted list, leaving the original tuple unchanged.
๐ŸŒ
Google
developers.google.com โ€บ google for education โ€บ python โ€บ python sorting
Python Sorting | Python Education | Google for Developers
Custom sorting can be achieved using the key= argument with sorted(), specifying a function to determine the sorting value for each element. Tuples are immutable, fixed-size collections, similar to lists but unable to be changed after creation.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ built-in โ€บ sorted
Python sorted()
We can use an optional reverse parameter to sort the list in descending order. For example, ... # sorting the numbers in descending order sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers) # Output: [13, 11, 9, 7, 3, 2] Here, sorted(iterable, reverse = True) sorts the list in descending order. The sorted() method accepts another optional parameter- the key function. For example, ... Here, len is Python's built-in function that counts the length of an element.
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-sort.html
Python Sorting
By default in Python, uppercase chars come before lowercase chars, so uppercase strings will sort to the front of the list: >>> strs = ['donut', 'ZEBRA', 'BANANA', 'apple'] >>> sorted(strs) ['BANANA', 'ZEBRA', 'apple', 'donut'] One possible fix it to convert the strings to all upper or lower case, although this is not the best looking solution. If the user...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_list_sort.asp
Python List sort() Method
Python Examples Python Compiler ... Q&A Python Bootcamp Python Certificate Python Training ... The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria...
Find elsewhere
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ list โ€บ sort
Python List sort()
cities = ["Tokyo", "London", "Washington D.C"] # sort in dictionary order cities.sort() print(f"Dictionary order: {cities}") # sort in reverse dictionary order cities.sort(reverse = True) print(f"Reverse dictionary order: {cities}")
๐ŸŒ
Python Reference
python-reference.readthedocs.io โ€บ en โ€บ latest โ€บ docs โ€บ functions โ€บ sorted.html
sorted โ€” Python Reference (The Right Way) 0.1 documentation
>>> sorted(['A', 'b', 'C']) ['A', 'C', 'b'] >>> sorted(['A', 'b', 'C'], key=lambda x: x.lower()) ['A', 'b', 'C'] >>> sorted(((1, ), (1, 2, 3), (1, 2))) [(1,), (1, 2), (1, 2, 3)] >>> sorted(((9, ), (1, 2, 3), (1, 2)), key=lambda x: sum(x)) [(1, 2), (1, 2, 3), (9,)]
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ builtin-functions โ€บ sorted
sorted() | Pythonโ€™s Built-in Functions โ€“ Real Python
The built-in sorted() function returns a new sorted list from the elements of any iterable passed to it.
Top answer
1 of 4
13

The function you pass in to key is given each of the items that are being sorted, and returns a "key" that Python can sort by. So, if you want to sort a list of strings by the reverse of the string, you could do this:

list_of_strings.sort(key=lambda s: s[::-1])

This lets you specify the value each item is sorted by, without having to change the item. That way, you don't have to build a list of reversed strings, sort that, then reverse them back.

# DON'T do this

data = ['abc', 'def', 'ghi', 'jkl']
reversed_data = [s[::-1] for s in data]
reversed_data.sort()
data = [s[::-1] for s in reversed_data]

# Do this

data.sort(key=lambda s: s[::-1])

In your case, the code is sorting each item by the second item in the tuple, whereas normally it would initially sort by the first item in the tuple, then break ties with the second item.

2 of 4
8
>>> votes = {'Charlie': 20, 'Able': 10, 'Baker': 20, 'Dog': 15}

If we apply .items() on the votes dictionary above we get:

>>> votes_items=votes.items()
>>> votes_items
[('Charlie', 20), ('Baker', 20), ('Able', 10), ('Dog', 15)]
#a list of tuples, each tuple having two items indexed 0 and 1

For each tuple, the first index [0] are the strings ('Charlie','Able','Baker','Dog') and the second index [1] the integers (20,10,20,15).

print(sorted(votes.items(), key = lambda x: x[1])) instructs python to sort the items(tuples) in votes using the second index [1] of each tuple, the integers, as the basis of the sorting.

Python compares each integer from each tuple and returns a list that has ranked each tuple in ascending order (this can be reversed with the reverse=True argument) using each tuple's integer as the key to determine the tuple's rank,

Where there is a tie in the key, the items are ranked in the order they are originally in the dictionary. (so ('Charlie', 20) is before ('Baker', 20) because there is a 20==20 tie on the key but ('Charlie', 20) comes before ('Baker', 20) in the original votes dictionary).

The output then is:

 [('Able', 10), ('Dog', 15), ('Charlie', 20), ('Baker', 20)]

I hope this makes it easier to understand.

๐ŸŒ
Python
docs.python.org โ€บ 3.10 โ€บ howto โ€บ sorting.html
Sorting HOW TO โ€” Python 3.10.20 documentation
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:
Top answer
1 of 2
381

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

2 of 2
7

Another method is to explicitly convert the set into a list (using list() function) and sort the list.

s = {10, 39, 3}

s_list = list(s)
s_list.sort()    # sort in-place
# [3, 10, 39]

Since Python 3.7, dicts keep insertion order. So if you want to order a set but still want to be able to do membership checks in constant time, you can create a dictionary from the sorted list using dict.fromkeys() (the values are None by default).

s = {10, 39, 3}

s_sorted = dict.fromkeys(sorted(s))               # ascending order
# {3: None, 10: None, 39: None}

s_sorted = dict.fromkeys(sorted(s, reverse=True)) # descending order
# {39: None, 10: None, 3: None}
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ python โ€บ built-in functions โ€บ sorted()
Python | Built-in Functions | sorted() | Codecademy
August 11, 2025 - This codebyte example uses sorted() with the key parameter set to len to sort the words list based on the length of its items: ... Yes, you can set the reverse parameter in sorted() to True to sort in descending order.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-sort-how-to-sort-a-list-in-python
Python .sort() โ€“ How to Sort a List in Python
March 8, 2022 - Descending (or decreasing) order ... To sort list items in descending order, you need to use the optional reverse parameter with the sort() method, and set its value to True....
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ how-to-sort-a-list-in-python
How to sort a list in Python | Codecademy
Learn how to sort lists in Python using `.sort()` and `sorted()`. Explore custom sorting with keys, descending order sorting, and apply real-world sorting techniques efficiently.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ sorting-in-python
Sorting in Python Tutorial | DataCamp
July 22, 2020 - Get your team access to the full DataCamp for business platform. The sort() method is a built-in Python method that, by default, sorts the list in ascending order.