Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Lambda

A lambda is a small function without a name, written in one expression. It is handy when a function is needed only once, for example to tell sorted how to compare items. The syntax is lambda parameters: expression, and the value of the expression is returned automatically.

lambda and def

These two definitions make the same function:

def double(x):
    return x * 2

double_too = lambda x: x * 2
add = lambda a, b: a + b
print(double(5), double_too(5), add(3, 4))
Output
10 10 7

A lambda may only contain a single expression: no statements such as if blocks, loops or assignments. Giving a lambda a name, as above, works but is considered poor style; when a function deserves a name, use def.

Sorting with a key

The most common use of lambda is the key argument of sorted, min, max and list.sort. The key function is called on each item, and the items are compared by its result:

students = [("Asha", 91), ("Ravi", 78), ("Meera", 85)]
print(sorted(students, key=lambda s: s[1]))
print(sorted(students, key=lambda s: s[1], reverse=True)[0][0])
words = ["banana", "Apple", "cherry"]
print(sorted(words))
print(sorted(words, key=lambda w: w.lower()))
print(max(students, key=lambda s: len(s[0])))
Output
[('Ravi', 78), ('Meera', 85), ('Asha', 91)]
Asha
['Apple', 'banana', 'cherry']
['Apple', 'banana', 'cherry']
('Meera', 85)

Plain sorted(words) already puts Apple first here, but only because capital letters come before small letters in Python's order: sorted(["banana", "apple", "Cherry"]) puts Cherry first. The key w.lower() compares the words without caring about case. max with a key returns the item itself, the whole tuple, chosen by the length of its name.

map and filter

map applies a function to every item, and filter keeps the items for which a function returns true. They return lazy iterators, so wrap them in list to see the results:

nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * n, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))
print([n * n for n in nums if n % 2 == 0])
Output
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
[4, 16, 36]

The last line does both jobs with a list comprehension, which most Python programmers find easier to read than map and filter with lambdas.

Functions that make functions

A function can return a lambda that remembers the values it was created with:

def multiplier(n):
    return lambda x: x * n

triple = multiplier(3)
print(triple(10), multiplier(5)(2))
Output
30 10

Practice exercises

  1. Sort a list of words by their last letter with a lambda key.
  2. Find the longest word in a list with max and key=len.
  3. Use filter with a lambda to keep the numbers above 50 from a list.
  4. Write make_greeter(greeting) that returns a lambda which greets a name.