Lambda Functions
You already know how to define functions with
A lambda is still an ordinary function. You can write it right where you need it and use it once, or store it in a name and call it as often as you like, just as you would a
def. Python also lets you write a tiny function in one line, with the word lambda. You met it when sorting. It's handy for a quick job, especially when you hand a function to another function, such as sorted(), map() or filter().A lambda is still an ordinary function. You can write it right where you need it and use it once, or store it in a name and call it as often as you like, just as you would a
def function.# normal function
def sq(n):
return n * n
# lambda version
sq_lambda = lambda n: n * n
print(sq(5)) # 25
print(sq_lambda(5)) # 25A lambda takes arguments before the colon, and its body is just one expression after it. There are no
Where do you see this in real programs? Imagine processing a list of sensor readings or calculating tax on invoice items. You need to transform each number quickly without writing a whole function definition.
return statements; Python automatically returns the result of that single line.Where do you see this in real programs? Imagine processing a list of sensor readings or calculating tax on invoice items. You need to transform each number quickly without writing a whole function definition.
map and filter
map() and filter() are built-in functions. Each one takes a function, then an iterable (anything a for loop can go through, such as a list), and uses the function on every item:map(func, items)runs each item through your function, and hands out the results.filter(test, items)runs your test on each item, and keeps only the items where it givesTrue.
# map: apply lambda to every number
scores = [70, 85, 92]
doubled = list(map(lambda s: s * 2, scores))
print(doubled) # [140, 170, 184]
# filter: keep only even numbers
nums = [3, 8, 15, 22, 9]
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens) # [8, 22]The example above doubled every score and filtered out odd numbers. Notice that
map transforms data while filter selects a subset.Sorting with a key
The
Imagine organising a playlist not alphabetically, but by song duration. You need a key that returns each track's length.
sorted() function accepts an optional key argument. This is where lambdas shine: you tell Python how to compare items by passing a small function that extracts the value used for sorting.Imagine organising a playlist not alphabetically, but by song duration. You need a key that returns each track's length.
# Sort these words from shortest to longest
words = ["banana", "kiwi", "apple", "fig"]
short_first = sorted(words, key=lambda w: len(w))
print(short_first)
# ['fig', 'kiwi', 'apple', 'banana']This example sorts words by how many letters they have. The lambda
lambda w: len(w) tells Python to compare each word by its length, not by its letters. For length alone, key=len does the same job. A lambda earns its place when the key needs working out: key=lambda w: w[-1] sorts by each word's last letter.