Python / Core Python Fundamentals Interview Questions
What is a lambda function in Python and when is it appropriate to use one?
A lambda is an anonymous, single-expression function defined inline. The syntax is lambda parameters: expression. It returns the value of the expression automatically — no return keyword needed. It can have any number of parameters, including defaults and *args.
double = lambda x: x * 2
print(double(5)) # 10
# Most common use: as a sort key
people = [('Alice', 30), ('Bob', 25), ('Carol', 35)]
people.sort(key=lambda p: p[1]) # sort by age
print(people) # [('Bob', 25), ('Alice', 30), ('Carol', 35)]
# With filter and map
evens = list(filter(lambda x: x % 2 == 0, range(10)))
doubled = list(map(lambda x: x * 2, [1, 2, 3]))When is a lambda appropriate? Use it for short, throwaway callables passed to sorted(), filter(), map(), or event handlers — situations where naming the function would make the code wordier without adding clarity. The PEP 8 style guide explicitly discourages assigning a lambda to a variable (like double = lambda x: x*2) because a def statement is clearer and gives the function a proper name visible in tracebacks.
Lambdas are limited to a single expression — no statements, no multi-line logic, no assignments. If the logic is even slightly complex, write a named function with def.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
