Lambda Functions
Think of a lambda as a disposable tool. You use it once, then throw it away. A regular
You already know how to define functions with
def function is like buying a hammer: you keep it in your toolbox for future projects. A lambda is like borrowing one from a neighbour just to hang a single picture.You already know how to define functions with
def. Python also lets you write tiny functions inline using the keyword lambda. This saves space when you need a quick function only once, especially as an argument to another 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 that apply a callable to every item in an iterable. They work like assembly lines:map(func, iterable)takes each item, runs it through your function, and outputs the result.filter(pred, iterable)looks at each item and keeps only those where your test returnsTrue.
# 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
numbers = [3, 8, 15, 22, 9]
evens = list(filter(lambda n: n % 2 == 0, numbers))
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 their character count. The lambda
lambda w: len(w) tells Python to compare each word based on its length, not its letters.