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.

Answer from Cyphase on Stack Overflow
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ howto โ€บ sorting.html
Sorting Techniques โ€” Python 3.14.6 documentation
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...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_func_sorted.asp
Python sorted() Function
Python Examples Python Compiler ... Interview Q&A Python Bootcamp Python Training ... The sorted() function returns a sorted list of the specified iterable object....
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
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), it sorts by the second value, then the third if there are any ties in the second value, etc. Think of it like sorting words in alphabetical order. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Can someone explain the `key=` argument for the sorted function
Python Sorted() Docs The "key" argument accepts a function that the sorted algorithm will apply to each item and uses the function's output as the basis of the sort. A common function passed to key is str.lower, which converts the string to lowercase before sorting to prevent things like a capital Z coming before a lowercase a. In your example, for the key, each string is itself being "sorted", which would result in the number being the first value of your string. In [182]: sorted('T4est') Out[182]: ['4', 'T', 'e', 's', 't'] # T comes first because capital More on reddit.com
๐ŸŒ r/learnpython
8
3
June 27, 2025
Sorted function in Python dictionary - Stack Overflow
I have a dictionary and I need to print the contents of dictionary first sorted by "value" if there is any value tie then I need to use "key" as a tie breaker so that the keys t... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-sorted-function
Python sorted() Function - GeeksforGeeks
December 20, 2025 - sorted() function in Python returns a new sorted list from the elements of any iterable, such as a list, tuple, set, or string.
๐ŸŒ
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.
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-sort.html
Python Sorting
>>> sorted(strs, reverse=True) ['zebra', 'donut', 'banana', 'apple'] By default in Python, uppercase chars come before lowercase chars, so uppercase strings will sort to the front of the list:
Find elsewhere
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 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,)]
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ list-sort()
Python List sort(): Master Data Sorting | Learn Now
The Python sort() method organizes the elements of a list in ascending or descending order.
๐ŸŒ
Google
developers.google.com โ€บ google for education โ€บ python โ€บ python sorting
Python Sorting | Python Education | Google for Developers
The sorted() function is the easiest way to sort a list, returning a new sorted list without changing the original.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can someone explain the `key=` argument for the sorted function
r/learnpython on Reddit: Can someone explain the `key=` argument for the sorted function
June 27, 2025 -

Hi,

So I was doing a code challenge and it's about sorting a string in numerical order based on the integer as part of the string, e.g:

"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"

I did it by creating a list with placeholder values and then assigned the values based on the number identified, see:

def order(sentence):
  temp = sentence.split()
  result = [0 for x in range(len(temp))]

  for item in temp:
    for char in item:
      if char.isnumeric():
        num = int(char)
        result[num-1] = item

  return " ".join(result)

I was just looking at other solutions and saw this cool one liner:

return sorted(temp, key=lambda w:sorted(w))

But I don't quite understand how it works :(

I have used the key= argument in the past, for example sorting by the size of the string, i.e key=len

The lambda uses a variable, w and passes it through sorted, but how does that sort by the number included in the string?

๐ŸŒ
Hyperskill
hyperskill.org โ€บ university โ€บ python โ€บ sorting-and-sort-in-python
Python sort() and sorted(): Sort Lists, Strings & Dicts
2 weeks ago - The Python sort() function is used to sort elements in a list. By default, it arranges elements in ascending order and modifies the original list in-place.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ built-in โ€บ sorted
Python sorted()
The sorted() method sorts the elements of the given iterable in ascending order and returns it. In this tutorial, we will learn about the Python sorted() function with the help of examples.
๐ŸŒ
University of Pittsburgh
sites.pitt.edu โ€บ ~naraehan โ€บ python3 โ€บ sorting.html
Python 3 Notes: Sorting
Python 3 Notes [ HOME | LING 1330/2330 ] Sorting << Previous Note Next Note >> On this page: Sorting a list/tuple/string/dictionary with sorted(), list.reverse() and list.sort(). Sorting with sorted() Need a list sorted? sorted() is the function to use. It takes a list as an argument and returns ...
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ HowTo โ€บ Sorting
HowTo/Sorting
So for example the original list ... 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 ...
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ functions.html
Built-in Functions โ€” Python 3.14.6 documentation
The sort algorithm uses only < comparisons between items. While defining an __lt__() method will suffice for sorting, PEP 8 recommends that all six rich comparisons be implemented.
๐ŸŒ
Kanaries
docs.kanaries.net โ€บ topics โ€บ Python โ€บ python-sort-list
Python Sort: Complete Guide to sorted(), list.sort(), and Custom Sorting โ€“ Kanaries
February 11, 2026 - This approach works particularly well when exploring unfamiliar datasets or presenting findings to non-technical stakeholders who need to understand data patterns without running Python code. The sorted() function returns a new sorted list and works with any iterable, leaving the original unchanged.
๐ŸŒ
Medium
medium.com โ€บ @tihomir.manushev โ€บ sorting-in-python-list-sort-vs-sorted-361e4da8880e
Sorting in Python: list.sort() vs. sorted() | by Tihomir Manushev | Medium
October 18, 2025 - Think of sorted() as your friendly, neighborhood sorting utility. Itโ€™s a built-in function, which means itโ€™s not tied to any specific object type. You can hand it almost any collection of items โ€” what Python calls an โ€œiterableโ€ โ€” and it will know what to do.