I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.

For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.

For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.

  1. Using lamba ultimately means you don't have to write (define) an entire function. Lambda functions are created, used, and immediately destroyed - so they don't funk up your code with more code that will only ever be used once. This, as I understand it, is the core utility of the lambda function and its application for such a role is broad. Its syntax is purely a convention, which is in essence the nature of programmatic syntax in general. Learn the syntax and be done with it.

Lambda syntax is as follows:

lambda input_variable(s): tasty one liner

where lambda is a python keyword.

e.g.

In [1]: f00 = lambda x: x/2

In [2]: f00(10)
Out[2]: 5.0

In [3]: (lambda x: x/2)(10)
Out[3]: 5.0

In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0

In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
  1. The idea behind the key argument is that it should take in a set of instructions that will essentially point the 'sorted()' function at those list elements which should be used to sort by. When it says key=, what it really means is: As I iterate through the list, one element at a time (i.e. for e in some_list), I'm going to pass the current element to the function specifed by the key argument and use that to create a transformed list which will inform me on the order of the final sorted list.

Check it out:

In [6]: mylist = [3, 6, 3, 2, 4, 8, 23]  # an example list
# sorted(mylist, key=HowToSort)  # what we will be doing

Base example:

# mylist = [3, 6, 3, 2, 4, 8, 23]
In [7]: sorted(mylist)
Out[7]: [2, 3, 3, 4, 6, 8, 23]  
# all numbers are in ascending order (i.e.from low to high).

Example 1:

# mylist = [3, 6, 3, 2, 4, 8, 23]
In [8]: sorted(mylist, key=lambda x: x % 2 == 0)

# Quick Tip: The % operator returns the *remainder* of a division
# operation. So the key lambda function here is saying "return True 
# if x divided by 2 leaves a remainer of 0, else False". This is a 
# typical way to check if a number is even or odd.

Out[8]: [3, 3, 23, 6, 2, 4, 8]  
# Does this sorted result make intuitive sense to you?

Notice that my lambda function told sorted to check if each element e was even or odd before sorting.

BUT WAIT! You may (or perhaps should) be wondering two things.

First, why are the odd numbers coming before the even numbers? After all, the key value seems to be telling the sorted function to prioritize evens by using the mod operator in x % 2 == 0.

Second, why are the even numbers still out of order? 2 comes before 6, right?

By analyzing this result, we'll learn something deeper about how the 'key' argument really works, especially in conjunction with the anonymous lambda function.

Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:

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.

We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.

So what does the example using a modulo return? A boolean value: True == 1, False == 0. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.

[3, 6, 3, 2, 4, 8, 23] becomes [0, 1, 0, 1, 1, 1, 0]

Now we're getting somewhere. What do you get when you sort the transformed list?

[0, 0, 0, 1, 1, 1, 1]

Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - it is because sorting only happens once! Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even numbers from low to high, those values remain in their original order relative to one another.

The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?

Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.

So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?

That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.

Lets try and predict what happens when I run the following code.

In [9]: mylist = [(3, 5, 8), (6, 2, 8), (2, 9, 4), (6, 8, 5)]
In[10]: sorted(mylist, key=lambda x: x[1])

My sorted call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, 'for each element x in mylist, return the second index of that element, then sort all of the elements of the original list mylist by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple using the lambda function.

The pointer that will be used to sort would be:

[5, 2, 9, 8] # the second element of each tuple

Sorting this pointer list returns:

[2, 5, 8, 9]

Applying this to mylist, we get:

Out[10]: [(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]
# Notice the sorted pointer list is the same as the second index of each tuple in this final list

Run that code, and you'll find that this is the order. Try sorting a list of integers using this key function and you'll find that the code breaks (why? Because you cannot index an integer of course).

This was a long winded explanation, but I hope this helps to sort your intuition on the use of lambda functions - as the key argument in sorted(), and beyond.

Answer from PaulG on Stack Overflow
Top answer
1 of 10
293

I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.

For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.

For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.

  1. Using lamba ultimately means you don't have to write (define) an entire function. Lambda functions are created, used, and immediately destroyed - so they don't funk up your code with more code that will only ever be used once. This, as I understand it, is the core utility of the lambda function and its application for such a role is broad. Its syntax is purely a convention, which is in essence the nature of programmatic syntax in general. Learn the syntax and be done with it.

Lambda syntax is as follows:

lambda input_variable(s): tasty one liner

where lambda is a python keyword.

e.g.

In [1]: f00 = lambda x: x/2

In [2]: f00(10)
Out[2]: 5.0

In [3]: (lambda x: x/2)(10)
Out[3]: 5.0

In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0

In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
  1. The idea behind the key argument is that it should take in a set of instructions that will essentially point the 'sorted()' function at those list elements which should be used to sort by. When it says key=, what it really means is: As I iterate through the list, one element at a time (i.e. for e in some_list), I'm going to pass the current element to the function specifed by the key argument and use that to create a transformed list which will inform me on the order of the final sorted list.

Check it out:

In [6]: mylist = [3, 6, 3, 2, 4, 8, 23]  # an example list
# sorted(mylist, key=HowToSort)  # what we will be doing

Base example:

# mylist = [3, 6, 3, 2, 4, 8, 23]
In [7]: sorted(mylist)
Out[7]: [2, 3, 3, 4, 6, 8, 23]  
# all numbers are in ascending order (i.e.from low to high).

Example 1:

# mylist = [3, 6, 3, 2, 4, 8, 23]
In [8]: sorted(mylist, key=lambda x: x % 2 == 0)

# Quick Tip: The % operator returns the *remainder* of a division
# operation. So the key lambda function here is saying "return True 
# if x divided by 2 leaves a remainer of 0, else False". This is a 
# typical way to check if a number is even or odd.

Out[8]: [3, 3, 23, 6, 2, 4, 8]  
# Does this sorted result make intuitive sense to you?

Notice that my lambda function told sorted to check if each element e was even or odd before sorting.

BUT WAIT! You may (or perhaps should) be wondering two things.

First, why are the odd numbers coming before the even numbers? After all, the key value seems to be telling the sorted function to prioritize evens by using the mod operator in x % 2 == 0.

Second, why are the even numbers still out of order? 2 comes before 6, right?

By analyzing this result, we'll learn something deeper about how the 'key' argument really works, especially in conjunction with the anonymous lambda function.

Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:

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.

We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.

So what does the example using a modulo return? A boolean value: True == 1, False == 0. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.

[3, 6, 3, 2, 4, 8, 23] becomes [0, 1, 0, 1, 1, 1, 0]

Now we're getting somewhere. What do you get when you sort the transformed list?

[0, 0, 0, 1, 1, 1, 1]

Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - it is because sorting only happens once! Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even numbers from low to high, those values remain in their original order relative to one another.

The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?

Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.

So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?

That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.

Lets try and predict what happens when I run the following code.

In [9]: mylist = [(3, 5, 8), (6, 2, 8), (2, 9, 4), (6, 8, 5)]
In[10]: sorted(mylist, key=lambda x: x[1])

My sorted call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, 'for each element x in mylist, return the second index of that element, then sort all of the elements of the original list mylist by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple using the lambda function.

The pointer that will be used to sort would be:

[5, 2, 9, 8] # the second element of each tuple

Sorting this pointer list returns:

[2, 5, 8, 9]

Applying this to mylist, we get:

Out[10]: [(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]
# Notice the sorted pointer list is the same as the second index of each tuple in this final list

Run that code, and you'll find that this is the order. Try sorting a list of integers using this key function and you'll find that the code breaks (why? Because you cannot index an integer of course).

This was a long winded explanation, but I hope this helps to sort your intuition on the use of lambda functions - as the key argument in sorted(), and beyond.

2 of 10
207

key is a function that will be called to transform the collection's items before they are compared. The parameter passed to key must be something that is callable.

The use of lambda creates an anonymous function (which is callable). In the case of sorted the callable only takes one parameters. Python's lambda is pretty simple. It can only do and return one thing really.

The syntax of lambda is the word lambda followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while, for, if and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.

We can compare the use of lambda with that of def to create a function.

adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2

lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.

variable is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.

🌐
Reddit
reddit.com › r/learnpython › sorting with key=lambda
r/learnpython on Reddit: sorting with key=lambda
March 14, 2023 -
pairs= [(1,'one'),(2,'two'),(3,'three'),(4,"four"),(5,"five")]
pairs.sort(key=lambda pair: pair[1])

>>> pairs
[(5, 'five'), (4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

why is it sorted like that I didn't understand? Why can't I write a number greater than 1 in pair[1]?

Discussions

sorting with key=lambda
pair is a tuple consisting of two items. Index 0 is the first item, index 1 is the second item. There is no other item in the tuple for any other index value to be valid. More on reddit.com
🌐 r/learnpython
11
1
March 14, 2023
I need some help figuring out how key=lambda works
https://stackoverflow.com/questions/13669252/what-is-key-lambda I hope this post answers your question. I haven’t been practicing py for a while, so folks correct me if I’m wrong. Lambda is what you can use when you call an anonymous function (or a nameless function). It comes in handy when you only need to use the function once, and there’s no point storing it elsewhere or giving it a name. In this case, I think it’s taking the argument team, and passing it into the lambda function. counts[team], I assume, will give a number corresponding to the team’s winning rate. That will be used as the key to sort the teams. Reverse=True means it’s sorted in the order of large to small (descending), instead of small to large (ascending). I’m typing on my phone so I apologize if anything is hard to read. More on reddit.com
🌐 r/cs50
2
5
August 9, 2022
how does key argument in sorted() works with lambda function
The lambda is called with each element internally. This simple filter variant might make how lambdas can be used clearer: def my_filter(predicate, items): new_list = [] for item in items: # Call the passed function (lambda) if predicate(item): new_list.append(item) return new_list print(my_filter(lambda n: n > 5, range(10))) # Prints [6, 7, 8, 9] The difference between the cases is here, my_filter is using the passed function to do filtering. With sorted, it's using the passed function to access members (or something similar) of each element. More on reddit.com
🌐 r/learnpython
13
2
January 14, 2023
Why use key lambda x : x here?

'key lambda x: x' in the signature of the function

it means that's the default sorting method (eg by the item's value itself) if the key argument isn't provided in the call to counting_sort.

and also why use the key(x) in line 4 above?

to make the entry in the defaultdict to be the value that the caller wants the result to be sorted on.

How would it be different than if I were to remove the 'key Lambda x : x' from the signature, so the function only accepts variable 'A', and in the code on line 4 if I got rid of the 'key(x)' and just used 'x'?

You then can't use any other sorting than the item value itself.

More on reddit.com
🌐 r/learnpython
3
4
December 6, 2018
🌐
Medium
johngrant.medium.com › python-list-sorting-keys-lambdas-1903b2a4c949
Python — List Sorting, Keys & Lambdas | by John Grant | Medium
July 22, 2016 - They syntax for a lambda is: ... ... 7, 10, 0, 57, 54), ‘2.61’] the lambda then returns the first element of the list, in this case the element that corresponds to the datetime object....
🌐
freeCodeCamp
freecodecamp.org › news › lambda-sort-list-in-python
Lambda Sorted in Python – How to Lambda Sort a List
March 16, 2023 - In this article, you’ll learn how to sort a list with the lambda function. ... You can sort a list with the sort() method and sorted() function. The sort() method takes two parameters – key and reverse.
🌐
Blogboard
blogboard.io › blog › knowledge › python-sorted-lambda
Python sort lambda - How to sort with lambda key function in Python
February 5, 2023 - # Sort by population cities = sorted(cities, key=lambda city: city['population'])
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › use-lambda-for-sorting-in-python
How to Use Lambda for Sorting in Python: A Quick Guide
January 20, 2025 - In Python, you can use the sorted() function or .sort() method to sort iterables. A lambda function is often used as a key to define custom sorting logic, making it easier to sort data based on specific criteria.
🌐
Python documentation
docs.python.org › 3 › howto › sorting.html
Sorting Techniques — Python 3.14.4 documentation
February 23, 2026 - The partial() function can reduce the arity of a multi-argument function making it suitable for use as a key-function. >>> from functools import partial >>> from unicodedata import normalize >>> names = 'Zoë Åbjørn Núñez Élana Zeke Abe Nubia Eloise'.split() >>> sorted(names, key=partial(normalize, 'NFD')) ['Abe', 'Åbjørn', 'Eloise', 'Élana', 'Nubia', 'Núñez', 'Zeke', 'Zoë'] >>> sorted(names, key=partial(normalize, 'NFC')) ['Abe', 'Eloise', 'Nubia', 'Núñez', 'Zeke', 'Zoë', 'Åbjørn', 'Élana']
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-sort-the-list-according-to-the-column-using-lambda
Python Program to Sort the list according to the column using lambda - GeeksforGeeks
July 12, 2025 - To sort a list of lists or tuples by the first column (index 0), we can use the sorted() function with a lambda function as the sorting key. ... a = [(3, 'fun!'), (1, 'Python'), (2, 'is')] # Sort by first column (index 0) sorted_data = sorted(a, ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › sort using lambda in python
Sort using Lambda in Python - Spark By {Examples}
May 9, 2024 - By using the list.sort() function you can order a list of numbers in ascending or descending order and use key=lambda to specify the sort function as python lambda, it also takes reverse param which is a boolean value that specifies whether ...
🌐
Linux Hint
linuxhint.com › sort-lambda-python
How to sort with lambda in Python – Linux Hint
# Declare a list of tuples tuple_list = [("HTML", 15, 'M01'), ("JavaScript", 10, 'M03'), ("Bootstrap", 5, 'M02')] # Sort the list based on the first item of the tuple sorted_list1 = sorted(tuple_list, key=lambda x: x[0]) # Print the first sorted list print("The sorted list based on the first item:\n", sorted_list1) # Sort the list based on the second item of the tuple sorted_list2 = sorted(tuple_list, key=lambda x: x[1]) # Print the second sorted list print("The sorted list based on the second item:\n", sorted_list2) # Sort the list based on the third item of the tuple sorted_list3 = sorted(tu
🌐
DEV Community
dev.to › kiani0x01 › how-to-sort-in-python-using-lambda-obg
How to sort in Python using Lambda - DEV Community
August 11, 2025 - Yet many developers focus on the default behavior of sorted() or .sort() and miss out on the power of the key parameter. What if you needed to sort complex objects, nested data, or even apply multiple criteria in a single pass? Ever wondered how to craft a one-liner solution that stays readable and efficient? The answer lies in Python’s anonymous functions—lambdas.
🌐
Medium
medium.com › @staytechrich › python-intermediate-015-sorting-with-sort-and-lambda-in-python-da56263b4061
Python Intermediate_015_ Sorting with .sort() and Lambda in Python | by CodeAddict | Medium
April 3, 2025 - The .sort() method modifies a list ... The key parameter allows you to define a custom sorting criterion, and a lambda function provides a concise way to specify that criterion without defining a separate function...
🌐
ThePythonGuru
thepythonguru.com › python-builtin-functions › sorted
Python sorted() function - ThePythonGuru.com
class Employee: def __init__(self, name, salary, age): self.name = name self.salary = salary self.age = age def __repr__(self): return self.__str__() def __str__(self): return "{0}:{1}:{2}".format(self.name, self.salary, self.age) e1 = Employee("Tom", 20000, 32) e2 = Employee("Jane", 50000, 36) e3 = Employee("Bob", 45000, 40) emp_list = [e2, e3, e1] print(sorted(emp_list, key=lambda x: x.name)) # sort Employee objects by name print(sorted(emp_list, key=lambda x: x.age)) # sort Employee objects by age print(sorted(emp_list, key=lambda x: x.salary)) # sort Employee objects by salary ... This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science.
🌐
Imperial College London
python.pages.doc.ic.ac.uk › 2022 › lessons › core10 › 05-lambda › 03-sorted.html
Lesson 10: I am Your Father > Lambda in sorted() | Python Programming (70053 Autumn Term 2022/2023) | Department of Computing | Imperial College London
You can use lambda function to sort the items by the values of the dictionary. This time, we will use the sorted() function rather than the mutable list.sort(). Just because we can! freq = {"python": 24, "cat": 78, "mat": 12, "aardvark": 1, "fish": 56} sorted_tuples = sorted(freq.items(), key=la...
🌐
Educative
educative.io › answers › how-to-sort-a-list-of-tuples-in-python-using-lambda
How to sort a list of tuples in Python using Lambda
The sorted() function takes the planets list as data, the lambda sets the function key parameter.
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Use the key Argument in Python (sorted, max, etc.) | note.nkmk.me
August 13, 2023 - Note that this will not work if run as a normal Python script. ... %%timeit sorted(l, key=lambda x: x['k1']) # 1.09 ms ± 35 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit sorted(l, key=operator.itemgetter('k1')) # 716 µs ± 28.2 µs per loop (mean ± std.
🌐
FavTutor
favtutor.com › blogs › python-sort-lambda
How to Sort with Lambda in Python | 7 Methods (With Code)
September 15, 2023 - In this code, the `sorted()` function is used with a lambda function as the `key` argument to sort the list of dictionaries based on the "age" key.
🌐
GeeksforGeeks
geeksforgeeks.org › python › ways-sort-list-dictionaries-values-python-using-lambda-function
Ways to sort list of dictionaries by values in Python - Using lambda function - GeeksforGeeks
November 14, 2025 - Explanation: (sorted(dic, key=lambda x: (x['age'], x['name'])): Sorts the list of dictionaries first by "age" in ascending order and if ages are equal then by "name" in alphabetic order.
🌐
Runestone Academy
runestone.academy › ns › books › published › fopp › Sorting › SortingaDictionary.html
16.4. Sorting a Dictionary — Foundations of Python Programming
g is a function that takes two parameters. The key function passed to sorted must always take just one parameter. ... The lambda function takes just one parameter, and calls g with two parameters.