λ

How to Use Lambda Functions in Python

PythonIntermediate

Create anonymous functions with lambda.

Code Example

Python
# Basic lambda
square = lambda x: x ** 2
print(f"5 squared = {square(5)}")

# Lambda with multiple arguments
add = lambda a, b: a + b
print(f"3 + 4 = {add(3, 4)}")

# Lambda with conditional
abs_val = lambda x: x if x >= 0 else -x
print(f"\nAbsolute of -5: {abs_val(-5)}")
print(f"Absolute of 3: {abs_val(3)}")

# Lambda with sorted()
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
by_grade = sorted(students, key=lambda s: s[1], reverse=True)
print(f"\nSorted by grade: {by_grade}")

# Lambda with map()
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(f"\nDoubled: {doubled}")

# Lambda with filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")

Explanation

Lambda creates small anonymous functions. Syntax: lambda arguments: expression. Useful with map(), filter(), sorted().

Related Tutorials