A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print(f())
foo

It is often used in functions such as sorted() that take a callable as a parameter (often the key keyword parameter). You could provide an existing function instead of a lambda there too, as long as it is a callable object.

Take the sorted() function as an example. It'll return the given iterable in sorted order:

>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']

but that sorts uppercased words before words that are lowercased. Using the key keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:

>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']

We had to create a separate function for that, we could not inline the def lowercased() line into the sorted() expression:

>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
  File "<stdin>", line 1
    sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
                                                           ^
SyntaxError: invalid syntax

A lambda on the other hand, can be specified directly, inline in the sorted() expression:

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']

Lambdas are limited to one expression only, the result of which is the return value.

There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.

Answer from Martijn Pieters on Stack Overflow
🌐
Reddit
reddit.com › r/cs50 › i need some help figuring out how key=lambda works
r/cs50 on Reddit: I need some help figuring out how key=lambda works
August 9, 2022 -

First of all, sorry for my english. I'm not using google and i can actually understand CS50 lectures, but you will see some typos here and there.

So, i'm actually doing Mat Lab 6, but i want to understand the whole code and not just the parts i need to write. The first thing i'm fighting with is:

for team in sorted(counts, key=lambda team: counts[team], reverse=True):
print(f"{team}: {counts[team] * 100 / N:.1f}% chance of winning")

Now i have been reading and looking for information and i already got things. Sorted is used to sort a list, dictionary, etc. So if i have, let's say:

list = [1, 2, 3, 4, 5]
for x in sorted(list, key=None):
    print(x)

Then i'll get 1, 2, 3, 4, 5 in that order.
Finally the key is in some manner to change the way the list is sorted. Lambda is a way to write a function in one single line during the for loop itself, so you don't need to make a whole new function.

Back to the code i posted at the begining, i kinda get that lambda is returning team's names, but i don't understand how Key is using this information to sort counts (a dictionary made out from names and rating of each team). Like, what's the point of using lambda here?

Anyway thank's in advance

What is the lambda function and how does it work? Apr 2, 2019
r/learnpython
7y ago
what in the hell is lambda Jul 21, 2021
r/learnpython
5y ago
can someone explain lambda to a beginner? Oct 10, 2024
r/learnpython
last yr.
How do lambda functions work in python?? May 16, 2019
r/learnprogramming
7y ago
More results from reddit.com
Top answer
1 of 4
129

A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print(f())
foo

It is often used in functions such as sorted() that take a callable as a parameter (often the key keyword parameter). You could provide an existing function instead of a lambda there too, as long as it is a callable object.

Take the sorted() function as an example. It'll return the given iterable in sorted order:

>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']

but that sorts uppercased words before words that are lowercased. Using the key keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:

>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']

We had to create a separate function for that, we could not inline the def lowercased() line into the sorted() expression:

>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
  File "<stdin>", line 1
    sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
                                                           ^
SyntaxError: invalid syntax

A lambda on the other hand, can be specified directly, inline in the sorted() expression:

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']

Lambdas are limited to one expression only, the result of which is the return value.

There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.

2 of 4
24

In Python, lambda is a keyword used to define anonymous functions(i.e., functions that don't have a name), sometimes called lambda functions (after the keyword, which in turn comes from theory).

Let's see some examples:

>>> # Define a lambda function that takes 2 parameters and sums them:
>>> lambda num1, num2: num1 + num2 
<function <lambda> at 0x1004b5de8>
>>> 
>>> # We can store the returned value in variable & call it:
>>> addition = lambda num1, num2: num1 + num2
>>> addition(62, 5)
67
>>> addition(1700, 29)
1729
>>> 
>>> # Since it's an expression, we can use it in-line instead:
>>> (lambda num1, num2: num1 + num2)(120, 1)
121
>>> (lambda num1, num2: num1 + num2)(-68, 2)
-66
>>> (lambda num1, num2: num1 + num2)(-68, 2**3)
-60
>>> 

Now let's see how this works in the context of sorted.

Suppose we have a list like so, with a mixture of integers and strings with numeric contents:

nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]

and that we would like to sort the values according to the number they represent: thus, the result should be ['-10', '-1', 1, '2', 3, 4, '5', '8'].

If we try to sort it using sorted, we get the wrong result:

>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums) # in 2.x
[1, 3, 4, '-1', '-10', '2', '5', '8']
>>> # In 3.x, an exception is raised instead

By using a key for sorted, however, we can sort the values according to the result of applying the key function to each value:

>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums, key=int)
['-10', '-1', 1, '2', 3, 4, '5', '8']
>>> 

Since lambda creates a callable (specifically, a function), we can use one for the key:

>>> names = ["Rishikesh", "aman", "Ajay", "Hemkesh", "sandeep", "Darshan", "Virendra", "Shwetabh"]
>>> names2 = sorted(names)
>>> names2
['Ajay', 'Darshan', 'Hemkesh', 'Rishikesh', 'Shwetabh', 'Virendra', 'aman', 'sandeep']
>>> # Let's use a lambda to get a case-insensitive sort:
>>> names3 = sorted(names, key=lambda name:name.lower())
>>> names3
['Ajay', 'aman', 'Darshan', 'Hemkesh', 'Rishikesh', 'sandeep', 'Shwetabh', 'Virendra']
>>>
Discussions

python - What does this mean: key=lambda x: x[1] ? - Stack Overflow
where is 'x' assigned a value? ... upon a key, from a list produced by the lambda (inline function) but, where is the value of 'x' assigned before being passed into the lambda? 2020-01-01T21:28:44.037Z+00:00 ... Save this answer. ... Show activity on this post. From a reference for Python 3.7 ... More on stackoverflow.com
🌐 stackoverflow.com
python - Syntax behind sorted(key=lambda: ...) - Stack Overflow
I don't quite understand the syntax behind the sorted() argument: key=lambda variable: variable[0] Isn't lambda arbitrary? Why is variable stated twice in what looks like a dict? More on stackoverflow.com
🌐 stackoverflow.com
What the hell is a lambda?

tl;dr Lambda creates a function without a name and has slightly different syntax. It's nothing to be afraid of.

How is lambda used?

In Python, lambda is mostly just used as a shorter syntax for creating functions. Usually it's used for short, throw-away functions. For instance, if I want to sort a list of pairs by the second element (by default Python sorts by the first element) you'd write:

s = sorted(my_list, key=lambda x, y: y)

This is slightly idiomatic since you have to know about how sorted works in order to sort by key with a function like that.

You can even, oddly enough, give lambdas a name:

In  [1]: add_five = lambda x: x + 5
In  [2]: add_five(10)
Out [2]: 15

In tkinter, in order to get a button to perform a certain action, I use lambdas since they're lazily evaluated (meaning they won't be evaluated until they're called). Here's how you might think you'd do it with a traditional definition (very contrived, don't think too hard about what it might actually be doing):

def add_five(x):
    return x + 5

num = 10

someButtonObject.on_click(add_five(num))

The problem is that Python will evaluate add_five(num) exactly once - when I define it. But if the value of num changes during the course of my program, then that might not be what I want to do. If I want to call this function regardless of what num might be at the given moment, I'd have to do it like this:

someButtonObject.on_click(lambda: num + 5)

You can also use it for "partial evaluation." What this means is that you can quickly create a new function in which you've sort of filled out a few of the arguments ahead of time. For instance:

In  [1]: def complicated_add(users_operating_system, users_age_in_base_7, x, y):
    <optimize for user's age and OS>
    return x + y

In  [2]: myAdd = lambda x, y: complicated_add("Amiga", "26", x, y)

In  [3]: myAdd(4, 5)
Out [3]: 9

As a syntax note, remember that a lambda function cannot span multiple lines and a lambda function cannot contain a loop or if statement.

Where did lambda come from? Lambda functions have a history that goes well beyond Python. In fact, before computers in fact. The lambda calculus was invented by Alonzo Church to solve a math problem about the solvability of equations. Alan Turing solved the same problem independently and the two are mathematically equivalent (called the Church-Turing thesis). The lambda calculus modeled computation not as a machine with an infinite tape with read-write capabilities like Turing did, but as these very simple functions that didn't even have a name. In the lambda calculus, each lambda function takes some arguments, then returns a new expression consisting of its arguments copied, deleted, and shuffled around a bit. It turns out that you only need to keep track of two variables (traditionally s and z) to calculate anything that can be calculated with this method.

Most computer scientists found it much easier to prove stuff using concepts like finite state machines, push-down machines, and turing machines. Programming languages based on concepts from lambda calculus are called "functional programming languages" (function meaning lambda functions). Haskell and LISP are the biggest examples, although the pedantic might want to point out that LISP isn't "purely" functional.

Python, as it was conceived, was probably meant to be a much more functional language than it wound up being. But those features slowly got muscled out. You even have to import reduce now. But lambda remains in it's strangely mutated form as an anonymous, lazily-evaluated function with syntax different from the rest of Python. This isn't because of any theoretical reason, but just because it's proved to be a handy little feature that comes up quite often.

More on reddit.com
🌐 r/learnpython
10
3
July 17, 2015
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
🌐
W3Schools
w3schools.com › python › ref_keyword_lambda.asp
Python lambda Keyword
Python Overview Python Built-in ... Study Plan Python Interview Q&A Python Training ... The lambda keyword is used to create small anonymous functions....
🌐
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 - Explanation: key=lambda x: x.modified tells Python to use the modified attribute of each element in the list a as the sorting criterion.
🌐
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: ... So when I used — list.sort(key=lambda r:r[0]) lambda r:r[0] is an anonymous function with a single argument, r which would in this case was a list, e.g.: [datetime.datetime(2016, 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.
🌐
Blogboard
blogboard.io › blog › knowledge › python-sorted-lambda
Python sort lambda - How to sort with lambda key function in Python
February 5, 2023 - The official Python docs explain this in simple terms: Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.
Find elsewhere
🌐
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.
🌐
Python Morsels
pythonmorsels.com › lambda-expressions
Python's lambda functions - Python Morsels
October 25, 2023 - See Overusing lambda expressions in Python for my opinions on avoiding lambda expressions. Lambda expressions are often very handy when using functions or classes that involve passing functions around. For example, you'll often see lambda expressions used with the built-in sorted function: >>> items = ["2 tomatoes", "1 avocado", "6 bananas", "4 clementines"] >>> sorted(items, key=lambda item: int(item.split()[0])) ['1 avocado', '2 tomatoes', '4 clementines', '6 bananas']
🌐
Quora
pythonlearners.quora.com › What-is-the-meaning-of-key-lambda-in-Python
http://www.quora.com/What-is-the-meaning-of-key-lambda-in-Python/answer/Tony-Flury
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
🌐
Python Tips
book.pythontips.com › en › latest › lambdas.html
19. Lambdas — Python Tips 0.1 documentation
You might want to use lambdas when you don’t want to use a function twice in a program. They are just like normal functions and even behave like them. ... a = [(1, 2), (4, 1), (9, 10), (13, -3)] a.sort(key=lambda x: x[1]) print(a) # Output: [(13, -3), (4, 1), (1, 2), (9, 10)]
🌐
Python Basics
python-basics-tutorial.readthedocs.io › en › latest › functions › lambda.html
Lambda functions - Python Basics
In the next example, a lambda function is created within a function call. However, there is no global variable to store the values of the lambda function: 1>>> count = ["1", "123", "1000"] 2>>> max(count) 3'123' 4>>> max(count, key=lambda val: int(val)) 5'1000'
🌐
freeCodeCamp
freecodecamp.org › news › python-lambda-functions
Python Lambda Functions – How to Use Anonymous Functions with Examples
February 24, 2023 - Lambda functions, also known as anonymous functions, are small, one-time-use functions in Python. You can define them using the lambda keyword followed by the function's inputs, a colon, and the function's expression.
🌐
Real Python
realpython.com › ref › keywords › lambda
lambda | Python Keywords – Real Python
In Python, the lambda keyword creates anonymous functions, also known as lambda functions. These functions are defined using the lambda keyword followed by a list of parameters, a colon, and an expression.
🌐
YouTube
youtube.com › watch
How to Use Python Lambda With the Sort Method - YouTube
You’ll see how to use a lambda for the key of the sort() method of lists. sort() has two parameters. key is None by default. reverse is False by default.You ...
Published: August 22, 2019
🌐
Python documentation
docs.python.org › 3 › howto › sorting.html
Sorting Techniques — Python 3.14.8 documentation
>>> student_tuples = [ ... ('john', 'A', 15), ... ('jane', 'B', 12), ... ('dave', 'B', 10), ... ] >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Top answer
1 of 10
296

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
208

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.

🌐
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, key=lambda x: x[0]) print(sorted_data)
🌐
Learn By Example
learnbyexample.org › python-lambda-function
Python Lambda Function - Learn By Example
April 23, 2020 - This function directly changes the behavior of the key function itself. Here are some key functions: ... In the following example, a lambda is assigned to the key argument so that the list of students is sorted by their age rather than by name.