map() | filter() | Lambda Functions
M3-R5.1 · Chapter 6: Functions · 8 min read
Lambda Functions
Definition: A lambda function is a small, anonymous (nameless) function defined using the lambda keyword.
It can have any number of parameters but only ONE expression. The expression is evaluated and returned automatically.
3.1 Syntax
|
Syntax |
Description |
|
lambda parameters : expression |
Anonymous function — expression is returned implicitly |
3.2 Structure Breakdown
lambda x , y : x + y
where -
lambda - > keyword
x -> parameter 1
y -> parameter 2
x+y -> expression (auto-returned)
3.3 Basic Examples
Example 1 — Simple addition
add = lambda a, b: a + b
print(add(3, 7)) # 10
Example 2 — Square of a number
square = lambda x: x ** 2
print(square(5)) # 25
Example 3 — Check even or odd
is_even = lambda n: n % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # False
Example 4 — No arguments
greet = lambda: 'Hello, World!'
print(greet()) # Hello, World!
Example 5 — Default parameter
greet = lambda name='Python': f'Hello, {name}!'
print(greet()) # Hello, Python!
print(greet('Alice')) # Hello, Alice!
Note - In Our syllabus we have to study about only lambda function bt the labda function is used in map and filter so we study these function also..
1. The map() Function
Definition: map() applies a given function to every item in an iterable (list, tuple, etc.) and returns a map object (an iterator) containing the results.
1.1 Syntax
|
Syntax |
Description |
|
map(function, iterable1 [, iterable2 ...]) |
Applies function to each element of iterable(s) |
1.2 Parameters
function -> The function to apply (built-in, user-defined, or lambda)
iterable -> Any iterable object (list, tuple, set, string, range ...)
-> Multiple iterables can be passed (function must accept that many args)
1.3 Return Value
Returns a map object (lazy iterator). Convert to list using list() to view results.
1.4 Examples
Example 1 — Square each number
numbers = [1, 2, 3, 4, 5]
def square(x):
return x * x
result = map(square, numbers) # <map object>
print(list(result)) # Output: [1, 4, 9, 16, 25]
Example 2 — Convert strings to uppercase
words = ['python', 'map', 'filter', 'lambda']
upper = list(map(str.upper, words))
print(upper) # ['PYTHON', 'MAP', 'FILTER', 'LAMBDA']
Example 3 — map() with multiple iterables
a = [1, 2, 3]
b = [10, 20, 30]
result = list(map(lambda x, y: x + y, a, b))
print(result) # [11, 22, 33]
Example 4 — Using built-in function with map()
str_nums = ['1', '2', '3', '4']
int_nums = list(map(int, str_nums)) # Convert strings to integers
print(int_nums) # [1, 2, 3, 4]
|
Key Points about map() map() does NOT modify the original iterable — it returns a new map object. It is lazy — elements are processed only when consumed (e.g., via list()). With multiple iterables, it stops at the shortest one. More memory-efficient than list comprehension for very large datasets. |
2. The filter() Function
Definition: filter() constructs an iterator from elements of an iterable for which a function returns True. It filters (selects) elements based on a condition.
2.1 Syntax
|
Syntax |
Description |
|
filter(function, iterable) |
Returns elements for which function returns True |
2.2 Parameters
function -> A function that returns True or False (predicate function)
-> If None is passed, removes all falsy values (0, None, '', [], False)
iterable -> Any iterable (list, tuple, set, range ...)
2.3 Return Value
Returns a filter object (lazy iterator). Use list() to convert it.
2.4 Examples
Example 1 — Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(n):
return n % 2 == 0
evens = list(filter(is_even, numbers))
print(evens) # [2, 4, 6, 8, 10]
Example 2 — Filter positive numbers
nums = [-3, -1, 0, 2, 5, -7, 8]
positives = list(filter(lambda x: x > 0, nums))
print(positives) # [2, 5, 8]
Example 3 — Filter non-empty strings
names = ['Alice', '', 'Bob', None, 'Charlie', '']
valid = list(filter(None, names)) # None removes falsy values
print(valid) # ['Alice', 'Bob', 'Charlie']
|
Key Points about filter() filter() keeps elements for which the function returns True. Passing None as the function removes all falsy values (0, False, None, '', [], {}). Like map(), filter() is lazy — evaluated on demand. Original iterable is never modified. |
3.4 Lambda with map()
Combine lambda and map() to transform each element inline — no need to define a separate function.
# Double each number
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
print(doubled) # [2, 4, 6, 8, 10]
# Celsius to Fahrenheit
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit) # [32.0, 68.0, 98.6, 212.0]
# Extract first character of each word
words = ['apple', 'banana', 'cherry']
initials = list(map(lambda w: w[0].upper(), words))
print(initials) # ['A', 'B', 'C']
3.5 Lambda with filter()
Combine lambda and filter() to select elements matching a condition — clean and concise.
# Filter numbers greater than 10
nums = [3, 15, 7, 22, 9, 11]
big = list(filter(lambda x: x > 10, nums))
print(big) # [15, 22, 11]
# Filter strings that start with 'A'
names = ['Alice', 'Bob', 'Anna', 'Charlie', 'Amy']
a_names = list(filter(lambda n: n.startswith('A'), names))
print(a_names) # ['Alice', 'Anna', 'Amy']
# Filter words longer than 4 characters
words = ['hi', 'hello', 'Python', 'is', 'awesome']
long_words = list(filter(lambda w: len(w) > 4, words))
print(long_words) # ['hello', 'Python', 'awesome']
3.6 Lambda with sorted()
Use lambda as the key parameter in sorted() to sort by custom criteria.
# Sort by second element of tuple
pairs = [(1, 'b'), (3, 'a'), (2, 'c')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # [(3, 'a'), (1, 'b'), (2, 'c')]
# Sort list of dicts by 'age'
people = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Carol', 'age': 35},
]
by_age = sorted(people, key=lambda p: p['age'])
for p in by_age:
print(p['name'], p['age'])
# Bob 25 | Alice 30 | Carol 35
# Sort strings by length
words = ['banana', 'fig', 'apple', 'kiwi']
by_len = sorted(words, key=lambda w: len(w))
print(by_len) # ['fig', 'kiwi', 'apple', 'banana']
3.7 lambda vs def — Detailed Comparison
|
Feature |
def Function |
Lambda Function |
|
Syntax |
def func(args): body |
lambda args: expression |
|
Name |
Always named |
Anonymous (no name) |
|
Statements |
Multiple statements allowed |
Single expression only |
|
return keyword |
Explicit return needed |
Implicit return |
|
Reusability |
Defined once, used anywhere |
Often used inline |
|
Docstring |
Supported |
Not supported |
|
Debugging |
Easier (has name) |
Harder (shows <lambda>) |
|
Best For |
Complex logic |
Short, one-liner functions |