LearnFrenzy
Sign in Take a free test

Python Programming · Topic 13 of 25

Lambda Functions Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Lambda Functions · Study material

A lambda is a small, anonymous function written in a single expression: lambda x: x * 2. Lambdas shine where a function is needed for a moment – as the key of sorted(), min() and max(), inside map() and filter(), or in a dictionary of operations. Interviews ask about their limits (one expression, no statements), the famous late-binding trap in loops, and when a list comprehension or a named function is better. This topic covers all of it, then 50 practice questions run on Python 3.

On this page

  • lambda syntax and how it compares with def
  • Lambdas as key functions for sorted, min and max
  • map(), filter() and reduce()
  • Conditional expressions inside a lambda
  • Closures and the late-binding trap
  • operator.itemgetter and functools.partial

Writing a lambda

lambda parameters: expression creates a function object that returns the value of the expression. It can take any number of parameters, including defaults, *args and **kwargs, but its body must be a single expression: no return, no assignments (except :=), no loops or if statements. Its __name__ is <lambda>, which makes tracebacks less clear – one reason PEP 8 says not to assign a lambda to a name; use def instead.

square = lambda x: x * x                 # lambda parameters: expression
add = lambda a, b=10: a + b              # default arguments work too
greet = lambda: "Hello!"                 # no parameters

def square_def(x):                       # the equivalent def
    return x * x

print(square(7), add(5), add(5, 1), greet())
print(square(4) == square_def(4))
print(square.__name__, square_def.__name__)   # lambdas are anonymous
print((lambda n: n % 2 == 0)(10))             # called immediately

Output

49 15 6 Hello!
True
<lambda> square_def
True

Lambdas as key functions

The most common use: sorted(), list.sort(), min() and max() accept key=, a function applied to each item before comparing. Returning a tuple sorts by several fields; negating a number reverses one field only.

students = [("Asha", 91, 20), ("Ravi", 78, 22), ("Meera", 91, 19), ("Dev", 66, 21)]

print(sorted(students, key=lambda s: s[1]))                    # by marks
print(sorted(students, key=lambda s: (-s[1], s[0])))           # marks desc, then name
print(min(students, key=lambda s: s[2])[0])                    # youngest
print(max(students, key=lambda s: s[1]))                       # first of the toppers

words = ["Banana", "apple", "cherry", "date"]
print(sorted(words, key=lambda w: w.lower()))
print(sorted(words, key=lambda w: (len(w), w.lower())))

Output

[('Dev', 66, 21), ('Ravi', 78, 22), ('Asha', 91, 20), ('Meera', 91, 19)]
[('Asha', 91, 20), ('Meera', 91, 19), ('Ravi', 78, 22), ('Dev', 66, 21)]
Meera
('Asha', 91, 20)
['apple', 'Banana', 'cherry', 'date']
['date', 'apple', 'Banana', 'cherry']

map(), filter() and reduce()

map(f, iterable) applies f to each item; filter(f, iterable) keeps the items for which f returns a truthy value; functools.reduce(f, iterable, initial) combines the items into one value. map and filter return lazy iterators – wrap them in list() to see the values, and remember they can be consumed only once. In modern Python a list comprehension is often clearer than map/filter with a lambda.

from functools import reduce

prices = [120, 45, 300, 80]

with_gst = list(map(lambda p: round(p * 1.18, 2), prices))       # transform each item
expensive = list(filter(lambda p: p > 100, prices))              # keep matching items
total = reduce(lambda acc, p: acc + p, prices, 0)                # fold into one value
pairs = list(map(lambda a, b: a * b, [1, 2, 3], [10, 20, 30]))   # map over two lists

print(with_gst)
print(expensive, total, pairs)

# The same with comprehensions – often clearer
print([round(p * 1.18, 2) for p in prices] == with_gst, [p for p in prices if p > 100])

Output

[141.6, 53.1, 354.0, 94.4]
[120, 300] 545 [10, 40, 90]
True [120, 300]

Conditions inside a lambda

A lambda cannot contain an if statement, but it can use the conditional expression a if condition else b – even chained. Keep it short: if you need more than one line of logic, write a def.

grade = lambda m: "A" if m >= 90 else "B" if m >= 75 else "C" if m >= 40 else "F"
sign = lambda n: (n > 0) - (n < 0)                  # True/False behave as 1/0
safe_div = lambda a, b: a / b if b else None

print([grade(m) for m in [95, 80, 52, 30]])
print(sign(-7), sign(0), sign(12))
print(safe_div(10, 4), safe_div(1, 0))

Output

['A', 'B', 'C', 'F']
-1 0 1
2.5 None

Closures and the late-binding trap

A lambda can use variables from the surrounding scope; a lambda returned from a function remembers them (a closure). But those variables are looked up when the lambda is called, not when it is created. Lambdas built in a loop therefore all see the loop variable's final value. Capture the current value with a default argument: lambda i=i: i.

def multiplier(n):
    return lambda x: x * n          # the lambda remembers n (a closure)

double, triple = multiplier(2), multiplier(3)
print(double(5), triple(5))

# Late binding: a lambda looks up i when it is CALLED, not when it is created
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])

# Fix: freeze the current value with a default argument
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])

Output

10 15
[2, 2, 2]
[0, 1, 2]

Alternatives: operator and functools.partial

operator.itemgetter(1), attrgetter("price") and functions such as operator.mul replace common lambdas and are slightly faster. functools.partial(func, …) creates a new function with some arguments already filled in.

from functools import partial, reduce
from operator import itemgetter, attrgetter, mul

rows = [("pen", 20), ("book", 450), ("bag", 1200)]
print(sorted(rows, key=itemgetter(1), reverse=True))     # same as key=lambda r: r[1]
print(reduce(mul, [1, 2, 3, 4, 5]))                      # same as lambda a, b: a * b

binary = partial(int, base=2)                            # fix some arguments of a function
print(binary("1011"), binary("11111111"))

class Item:
    def __init__(self, name, price):
        self.name, self.price = name, price
items = [Item("tea", 20), Item("cake", 90)]
print([i.name for i in sorted(items, key=attrgetter("price"), reverse=True)])

Output

[('bag', 1200), ('book', 450), ('pen', 20)]
120
11 255
['cake', 'tea']

Common mistakes

  • Writing return or statements in a lambda – SyntaxError.
  • Lambdas in a loop that all return the last value – use a default argument.
  • Reusing a map or filter iterator – it is empty the second time.
  • Passing f(x) instead of f to map, filter or key – pass the function itself.
  • reduce() on an empty list without an initial value – TypeError.
  • Long, nested lambdas – hard to read and debug; use def.

Key points to remember

  • lambda args: expression – one expression, returned automatically.
  • Lambdas are ordinary function objects named <lambda>.
  • Use them for short key functions and callbacks.
  • map and filter are lazy, one-shot iterators.
  • Free variables are looked up at call time (late binding).
  • Prefer comprehensions to map/filter + lambda when clearer.
  • Name a function with def instead of assigning a lambda.

Frequently asked questions

Are lambdas faster than normal functions?

No. A lambda compiles to the same kind of function object as def; only the syntax differs.

Can a lambda have multiple lines?

No. It is limited to one expression. Brackets let you spread a long expression over several lines, but at that point a def is clearer.

When should I use map instead of a list comprehension?

When you already have a named function: map(str, nums) is concise. With a lambda, [x * 2 for x in nums] usually reads better than map(lambda x: x * 2, nums).

Where can I learn more?

Read Scope, Lambda and Recursion in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links