When you first learn Python, you will usually create functions with the def keyword. These are great when you need a block of code that you plan to reuse. However, Python also has a shorter way to create functions called lambda functions. These are sometimes called anonymous functions because they do not need a name.
What is a lambda function
A lambda function is a quick way of writing a small function in a single line. They are useful when you only need a function once or for a very short task.
The syntax is:
lambda arguments: expression
The word lambda starts the function, then you list the arguments, followed by a colon, and finally the expression that gets calculated and returned.
Basic example
Here is a simple lambda function that adds two numbers together:
add = lambda a, b: a + b
print(add(3, 5)) # prints 8
This does the same thing as writing a normal function with def, but it is shorter.
Using lambda with strings
We can also use lambda functions with strings like “LiddleBit”. For example, turning a name into uppercase:
shout = lambda text: text.upper()
print(shout("LiddleBit")) # prints LIDDLEBIT
Lambda inside other functions
Lambda functions are often used together with built-in Python functions like map, filter, and sorted. For example, you can sort a list of names by their length:
names = ["LiddleBit", "Sam", "Chris"]
sorted_names = sorted(names, key=lambda x: len(x))
print(sorted_names)
Here the lambda tells Python to sort by the length of each name instead of the default alphabetical order.
When to use lambda functions
Lambda functions are best for small, quick tasks where writing a full function would feel like too much. For anything longer or more complicated, stick to the regular def style so your code stays clear and easy to read.
Things to try yourself
- Write a lambda function that squares a number and test it with different values.
- Use
mapwith a lambda function to turn a list of names, including “LiddleBit”, into lowercase. - Use
filterwith a lambda function to find numbers greater than 10 in a list. - Sort a list of words by their last letter using
sortedwith a lambda.
Lambda functions may look unusual at first, but they are simply a quicker way to write short, throwaway functions. Once you get used to them, you will see how handy they can be in many everyday Python tasks.




