Python Lambda

Small anonymous functions.

✍️ 3 exercises + code challenge in this lesson

A lambda is a small anonymous function written in one line:

lambda arguments: expression

Lambdas are handy when a short function is needed only once, for example as the key for sorting, or with map() and filter().

Key Takeaways: Python Lambda

Mastering Python Lambda helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python Lambda Code Example

Python
square = lambda x: x * x
print(square(7))

students = [("Ali", 81), ("Sara", 94), ("Usman", 67)]
students.sort(key=lambda s: s[1], reverse=True)
print(students)

nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * 10, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))
Free sign-in required · Google login available

Python Lambda Practice Exercises

Check what you learned in “Python Lambda”.

/ 3 solved
Fill in the blank

Create a lambda that adds 10.

add_ten =  x: x + 10
✓ Correct! Not quite. Try again.
Multiple choice

How many expressions can a lambda contain?

✓ Correct! Not quite. Try again.
Code challenge

Sort the names by length using sorted() with a lambda key and print the result.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services