lambdaEasy Examples

Creates a small anonymous (unnamed) function in a single expression

Anonymous functions

Creating small inline functions with lambda.

python
square = lambda x: x ** 2
print(square(5))

add = lambda a, b: a + b
print(add(3, 4))

# Lambda with built-in functions
numbers = [5, 2, 8, 1, 9, 3]
print(sorted(numbers))
print(sorted(numbers, key=lambda x: -x))

words = ["banana", "apple", "cherry"]
print(sorted(words, key=lambda w: len(w)))
Expected Output
25
7
[1, 2, 3, 5, 8, 9]
[9, 8, 5, 3, 2, 1]
['apple', 'banana', 'cherry']

lambda creates a function in one expression. It is most useful as a key function for sorted(), map(), filter(), etc.

Want to try these examples interactively?

Open Easy Playground