Syntax

square = lambda x: x * x
print(square(5))   # 25

Equivalent to:

def square(x):
    return x * x

Where Lambdas Shine

pairs = [("a", 3), ("b", 1), ("c", 2)]
pairs.sort(key=lambda p: p[1])
# [('b',1), ('c',2), ('a',3)]
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda n: n % 2 == 0, nums))
squared = list(map(lambda n: n*n, nums))

When to Avoid Lambdas

๐Ÿ’ก For HKDSE, stick to def unless the question explicitly shows lambda syntax. Lambdas are rarely required but often useful in data-processing tasks.

Practise this on PyForm โ€” free

PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.

Open PyForm โ†’