Creating Lambda Functions and Using map(), filter(), and zip() in Python
Course: Python Training
Topic: Creating Lambda Functions and Using map(), filter(), and zip()
Course Link: Python Training Course at JustAcademy
Demo Link: Register for a Course Demo
Website: Visit JustAcademy
1. Introduction
Python provides several powerful features for working with functions and collections of data. Lambda functions allow programmers to create small anonymous functions, while map(), filter(), and zip() simplify common operations involving iterables such as lists, tuples, strings, and other sequences.
These features are commonly used in data processing, automation, analytics, sorting, report generation, and functional programming. They can reduce repetitive code and make certain operations more expressive.
- Lambda functions: Create small functions using the
lambda keyword.
- map(): Apply a function to each item in one or more iterables.
- filter(): Select items that satisfy a condition.
- zip(): Combine corresponding items from multiple iterables into tuples.
These tools return iterators in Python 3, so their results are often converted into lists or processed through loops when a concrete collection or visible output is needed.
2. Learning Objectives
- Understand anonymous functions and lambda expressions.
- Learn the syntax and limitations of lambda functions.
- Differentiate lambda functions from functions defined with
def.
- Use
map() to transform data.
- Use
filter() to select values that satisfy conditions.
- Use
zip() to combine related sequences.
- Combine lambda expressions with
map(), filter(), and zip().
- Understand iterators, lazy evaluation, and iterable lengths.
- Compare these techniques with list comprehensions and loops.
- Apply these concepts to practical Python projects.
3. Understanding Lambda Functions
3.1 What Is a Lambda Function?
A lambda function is a small anonymous function created with the lambda keyword. It can accept arguments and evaluate a single expression, returning the expression's result automatically.
Unlike a function defined with def, a lambda expression does not require a function name in its definition.
Syntax:
lambda parameters: expression
Example:
square = lambda number: number * number
print(square(5))
print(square(8))
Output:
25
64
Here, number is the parameter, and number * number is the expression. The resulting function is assigned to the variable square and called like any other function.
3.2 Creating a Lambda Function with Two Parameters
A lambda function can accept multiple parameters, separated by commas.
add = lambda a, b: a + b
print(add(10, 20))
print(add(15, 25))
Output:
30
40
The function accepts two arguments and returns their sum.
3.3 Lambda Functions with Three Parameters
calculate_total = lambda price, quantity, tax: price * quantity + tax
print(calculate_total(100, 3, 15))
Output:
315
The expression calculates the total cost by multiplying price by quantity and adding tax.
4. Lambda Functions vs. Regular Functions
Python supports both lambda expressions and named functions defined with def. Each has a useful role.
| Feature |
Lambda Function |
Regular Function |
| Definition |
Uses the lambda keyword. |
Uses the def keyword. |
| Name |
Often anonymous, but can be assigned to a variable. |
Usually has an explicit name. |
| Body |
Restricted to a single expression. |
Can contain multiple statements. |
| Return behavior |
Automatically returns the expression's result. |
Uses return when a value must be returned. |
| Documentation |
Limited support for descriptive documentation. |
Can include a docstring. |
| Typical use |
Short operations and inline callbacks. |
Reusable or complex logic. |
Regular function example:
def multiply(a, b):
return a * b
print(multiply(4, 6))
Output:
24
Equivalent lambda example:
multiply = lambda a, b: a * b
print(multiply(4, 6))
Output:
24
Both examples produce the same result. For complex operations, a named function is usually easier to understand, test, and maintain.
5. Lambda Functions with Conditional Expressions
A lambda expression can contain a conditional expression to choose between two values. It cannot contain a normal multi-statement if block.
check_number = lambda number: "Even" if number % 2 == 0 else "Odd"
print(check_number(8))
print(check_number(13))
Output:
Even
Odd
The expression checks the remainder after division by two. If the remainder is zero, it returns "Even"; otherwise, it returns "Odd".
5.1 Finding the Larger Number
larger = lambda a, b: a if a > b else b
print(larger(15, 25))
print(larger(40, 12))
Output:
25
40
5.2 Checking Eligibility
eligibility = lambda age: "Eligible" if age >= 18 else "Not eligible"
print(eligibility(22))
print(eligibility(16))
Output:
Eligible
Not eligible
6. What Is map() in Python?
6.1 Definition
The map() function applies a specified function to each item in an iterable and produces an iterator containing the resulting values.
Syntax:
map(function, iterable)
It can also accept multiple iterables:
map(function, iterable1, iterable2, ...)
When multiple iterables are supplied, the function must accept the corresponding number of arguments. Processing stops when the shortest iterable is exhausted.
6.2 Using map() with a Lambda Function
numbers = [1, 2, 3, 4, 5]
squares = map(lambda number: number ** 2, numbers)
print(list(squares))
Output:
[1, 4, 9, 16, 25]
The lambda calculates the square of each number. The map() function applies it to every item, and list() converts the resulting iterator into a list.
6.3 Converting Strings to Integers
The map() function is useful when converting several values from one data type to another.
values = ["10", "20", "30", "40"]
numbers = map(int, values)
print(list(numbers))
Output:
[10, 20, 30, 40]
Here, the built-in int() function is passed directly to map(). A lambda function is unnecessary because Python already provides the required conversion function.
6.4 Converting Names to Uppercase
names = ["riya", "aarav", "meera"]
uppercase_names = map(lambda name: name.upper(), names)
print(list(uppercase_names))
Output:
['RIYA', 'AARAV', 'MEERA']
6.5 Applying a Function to Multiple Iterables
When two iterables are passed to map(), the supplied function receives one item from each iterable per operation.
numbers1 = [10, 20, 30]
numbers2 = [1, 2, 3]
results = map(lambda a, b: a + b, numbers1, numbers2)
print(list(results))
Output:
[11, 22, 33]
The function calculates 10 + 1, 20 + 2, and 30 + 3.
6.6 Using map() Without Lambda
The function passed to map() can be a named function or a built-in function.
def double(number):
return number * 2
numbers = [2, 4, 6, 8]
result = map(double, numbers)
print(list(result))
Output:
[4, 8, 12, 16]
7. What Is filter() in Python?
7.1 Definition
The filter() function selects elements from an iterable based on a function that determines whether each element should be retained.
Syntax:
filter(function, iterable)
The supplied function is usually called a predicate. It should return a truthy value for items that should be kept and a falsy value for items that should be excluded.
7.2 Filtering Even Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = filter(lambda number: number % 2 == 0, numbers)
print(list(even_numbers))
Output:
[2, 4, 6, 8]
The lambda returns True when a number is divisible by two. Only those numbers are retained.
7.3 Filtering Odd Numbers
numbers = [10, 11, 12, 13, 14, 15]
odd_numbers = filter(lambda number: number % 2 != 0, numbers)
print(list(odd_numbers))
Output:
[11, 13, 15]
7.4 Filtering Numbers Greater Than a Value
numbers = [12, 45, 7, 60, 28, 90]
large_numbers = filter(lambda number: number > 30, numbers)
print(list(large_numbers))
Output:
[45, 60, 90]
7.5 Filtering Strings by Length
names = ["Raj", "Ananya", "Meera", "Om", "Kabir"]
long_names = filter(lambda name: len(name) > 4, names)
print(list(long_names))
Output:
['Ananya', 'Meera', 'Kabir']
7.6 Filtering with a Named Function
def is_positive(number):
return number > 0
numbers = [-5, 0, 10, -2, 8, 3]
positive_numbers = filter(is_positive, numbers)
print(list(positive_numbers))
Output:
[10, 8, 3]
7.7 Using filter() with None
If None is supplied as the first argument, filter() retains items that evaluate to True in a Boolean context.
values = [0, 1, "", "Python", None, 25, False]
result = filter(None, values)
print(list(result))
Output:
[1, 'Python', 25]
Values such as 0, "", None, and False are falsy, so they are excluded. Use this pattern only when removing all falsy values is the intended behavior.
8. What Is zip() in Python?
8.1 Definition
The zip() function combines corresponding elements from two or more iterables. It returns an iterator that yields tuples containing one item from each iterable.
Syntax:
zip(iterable1, iterable2, ...)
8.2 Combining Two Lists
names = ["Aarav", "Meera", "Kabir"]
scores = [85, 92, 78]
combined = zip(names, scores)
print(list(combined))
Output:
[('Aarav', 85), ('Meera', 92), ('Kabir', 78)]
The first name is paired with the first score, the second name with the second score, and so on.
8.3 Combining Three Lists
names = ["Riya", "Aarav", "Meera"]
ages = [21, 24, 22]
cities = ["Mumbai", "Pune", "Thane"]
students = zip(names, ages, cities)
print(list(students))
Output:
[('Riya', 21, 'Mumbai'),
('Aarav', 24, 'Pune'),
('Meera', 22, 'Thane')]
Each output tuple contains the corresponding name, age, and city.
8.4 Iterating with zip()
Instead of converting the result to a list, you can process each tuple directly in a loop.
products = ["Laptop", "Mouse", "Keyboard"]
prices = [55000, 800, 1500]
for product, price in zip(products, prices):
print(product, "costs", price)
Output:
Laptop costs 55000
Mouse costs 800
Keyboard costs 1500
8.5 What Happens When Iterable Lengths Differ?
By default, zip() stops as soon as the shortest iterable is exhausted. Any extra elements in longer iterables are not included in the result.
names = ["Aarav", "Meera", "Kabir"]
scores = [85, 92]
print(list(zip(names, scores)))
Output:
[('Aarav', 85), ('Meera', 92)]
The third name has no corresponding score, so it is excluded from the zipped result.
8.6 Using zip(strict=True)
In Python 3.10 and later, zip() supports the keyword argument strict=True. This raises a ValueError if the iterables have different lengths, which can help detect data alignment errors.
names = ["Aarav", "Meera"]
scores = [85, 92]
print(list(zip(names, scores, strict=True)))
Output:
[('Aarav', 85), ('Meera', 92)]
Both iterables have equal lengths, so the operation succeeds. If one iterable contains an extra item, iteration raises ValueError.
8.7 Unzipping Data with the * Operator
Unzipping means separating paired values into individual sequences. A common technique is to use zip(*pairs).
pairs = [("Aarav", 85), ("Meera", 92), ("Kabir", 78)]
names, scores = zip(*pairs)
print(names)
print(scores)
Output:
('Aarav', 'Meera', 'Kabir')
(85, 92, 78)
The unpacking operation works when there is at least one pair and the pairs have compatible lengths. Handle empty input separately if necessary.
9. Understanding Iterators and Lazy Evaluation
In Python 3, map(), filter(), and zip() return iterators instead of immediately creating complete lists. This behavior is known as lazy evaluation: values are produced as they are requested.
numbers = [1, 2, 3, 4]
result = map(lambda number: number * 10, numbers)
print(result)
print(list(result))
The first line of output displays a representation of a map iterator, similar to:
<map object at 0x...>
The exact memory address varies. The second output is:
[10, 20, 30, 40]
9.1 Why Lazy Evaluation Is Useful
- It avoids creating a complete output list immediately.
- It can reduce memory usage when processing large data streams.
- It allows results to be processed one item at a time.
- It can stop processing early when only a few results are needed.
9.2 Iterators Are Usually Exhausted After Use
Once an iterator has been consumed, its yielded items are not automatically available again.
numbers = [1, 2, 3]
result = map(lambda number: number * 2, numbers)
print(list(result))
print(list(result))
Output:
[2, 4, 6]
[]
The first call to list() consumes the iterator. The second call finds no remaining items. Create a new iterator if you need to repeat the operation.
10. Combining Lambda Functions with map()
Lambda functions and map() work together when each input item must be transformed using a short expression.
10.1 Doubling Numbers
numbers = [2, 4, 6, 8]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
Output:
[4, 8, 12, 16]
10.2 Converting Prices to Include Tax
prices = [100, 200, 300, 400]
tax_rate = 0.18
final_prices = list(
map(lambda price: round(price * (1 + tax_rate), 2), prices)
)
print(final_prices)
Output:
[118.0, 236.0, 354.0, 472.0]
The lambda calculates the price after adding an 18% tax rate.
10.3 Extracting First Characters
names = ["Ananya", "Kabir", "Meera", "Rahul"]
initials = list(map(lambda name: name[0], names))
print(initials)
Output:
['A', 'K', 'M', 'R']
11. Combining Lambda Functions with filter()
Use filter() with a lambda expression when you need to retain items that satisfy a simple condition.
11.1 Selecting Passing Scores
scores = [45, 72, 38, 90, 65, 28, 81]
passing_scores = list(filter(lambda score: score >= 40, scores))
print(passing_scores)
Output:
[45, 72, 90, 65, 81]
11.2 Selecting Affordable Products
prices = [250, 1200, 499, 3500, 799, 150]
affordable = list(filter(lambda price: price < 1000, prices))
print(affordable)
Output:
[250, 499, 799, 150]
11.3 Selecting Names Starting with a Letter
names = ["Aarav", "Meera", "Ananya", "Kabir", "Aditi"]
selected = list(filter(lambda name: name.startswith("A"), names))
print(selected)
Output:
['Aarav', 'Ananya', 'Aditi']
12. Combining Lambda Functions with zip()
Although zip() does not require a function, it can be combined with a lambda expression to process paired data.
12.1 Adding Corresponding Values
list_a = [10, 20, 30]
list_b = [1, 2, 3]
totals = list(
map(lambda pair: pair[0] + pair[1], zip(list_a, list_b))
)
print(totals)
Output:
[11, 22, 33]
The zip() function creates pairs, and map() applies the lambda to each pair.
12.2 Calculating Total Prices from Products and Quantities
prices = [100, 250, 80]
quantities = [2, 3, 5]
totals = list(
map(lambda price, quantity: price * quantity, prices, quantities)
)
print(totals)
Output:
[200, 750, 400]
Here, map() accepts two iterables directly, so a separate zip() call is unnecessary.
13. Combining map() and filter()
Data processing often involves two stages: filtering values that meet a condition and then transforming the selected values.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
squares = map(lambda x: x ** 2, even_numbers)
print(list(squares))
Output:
[4, 16, 36, 64, 100]
The program first selects even numbers and then calculates their squares.
13.1 Practical Example: Process Passing Scores
scores = [32, 75, 48, 91, 27, 68, 84]
passing_scores = filter(lambda score: score >= 40, scores)
updated_scores = map(lambda score: min(score + 5, 100), passing_scores)
print(list(updated_scores))
Output:
[80, 53, 96, 73, 89]
The program selects scores of at least 40 and then adds five points to each selected score, limiting the result to 100.
14. Comparing map(), filter(), and zip()
| Feature |
map() |
filter() |
zip() |
| Main purpose |
Transform each item. |
Select items based on a condition. |
Combine corresponding items. |
| Input |
A function and one or more iterables. |
A predicate function and an iterable. |
Two or more iterables, or one iterable. |
| Output |
Iterator of transformed results. |
Iterator of retained items. |
Iterator of tuples. |
| Function required? |
Yes. |
Usually; can use None for truth-value filtering. |
No. |
| Example |
map(lambda x: x * 2, nums) |
filter(lambda x: x > 5, nums) |
zip(names, scores) |
| Typical application |
Conversion or calculation. |
Validation or selection. |
Pairing records or aligned data. |
15. List Comprehensions vs. map() and filter()
List comprehensions often provide a concise and readable alternative to map() and filter(). The best choice depends on the task and the team's preferred coding style.
15.1 map() vs. List Comprehension
numbers = [1, 2, 3, 4]
# Using map()
squares_map = list(map(lambda x: x ** 2, numbers))
# Using a list comprehension
squares_comprehension = [x ** 2 for x in numbers]
print(squares_map)
print(squares_comprehension)
Output:
[1, 4, 9, 16]
[1, 4, 9, 16]
15.2 filter() vs. List Comprehension
numbers = [1, 2, 3, 4, 5, 6]
# Using filter()
even_filter = list(filter(lambda x: x % 2 == 0, numbers))
# Using a list comprehension
even_comprehension = [x for x in numbers if x % 2 == 0]
print(even_filter)
print(even_comprehension)
Output:
[2, 4, 6]
[2, 4, 6]
15.3 Which Approach Should You Choose?
- Use
map() when applying an existing function to every item is clear and concise.
- Use
filter() when selecting items based on a predicate improves readability.
- Use list comprehensions when transformation or filtering can be expressed naturally in one readable expression.
- Use regular loops when the logic involves multiple statements, complex branching, logging, or error handling.
- Use
zip() when corresponding items from multiple iterables must be processed together.
16. Practical Example: Student Result Processing
This example combines lambda functions, map(), filter(), and zip() to process student marks.
students = ["Aarav", "Meera", "Kabir", "Riya"]
marks = [85, 38, 92, 67]
student_records = list(zip(students, marks))
passing_students = list(
filter(lambda record: record[1] >= 40, student_records)
)
grade_records = list(
map(
lambda record: (
record[0],
record[1],
"Pass" if record[1] >= 40 else "Fail"
),
student_records
)
)
print("All records:", student_records)
print("Passing students:", passing_students)
print("Grades:", grade_records)
Output:
All records: [('Aarav', 85), ('Meera', 38), ('Kabir', 92), ('Riya', 67)]
Passing students: [('Aarav', 85), ('Kabir', 92), ('Riya', 67)]
Grades: [('Aarav', 85, 'Pass'), ('Meera', 38, 'Fail'), ('Kabir', 92, 'Pass'), ('Riya', 67, 'Pass')]
Explanation:
zip() combines each student's name with the corresponding mark.
filter() selects records with marks of at least 40.
map() adds a pass or fail label to every record.
list() materializes each iterator so the result can be displayed and reused.
17. Practical Example: Product Inventory
Product data can be combined, filtered, and transformed to calculate inventory values and identify products that need attention.
products = ["Laptop", "Mouse", "Keyboard", "Monitor"]
prices = [55000, 800, 1500, 12000]
stock = [5, 25, 12, 3]
inventory = list(zip(products, prices, stock))
inventory_value = list(
map(lambda item: (item[0], item[1] * item[2]), inventory)
)
low_stock = list(
filter(lambda item: item[2] < 5, inventory)
)
print("Inventory values:", inventory_value)
print("Low-stock products:", low_stock)
Output:
Inventory values: [('Laptop', 275000), ('Mouse', 20000), ('Keyboard', 18000), ('Monitor', 36000)]
Low-stock products: [('Monitor', 12000, 3)]
The program pairs each product with its price and stock count, calculates the total value of each product's stock, and selects products whose stock count is below five.
18. Common Mistakes and Troubleshooting
| Mistake |
Why It Happens |
Solution |
| Writing multiple statements in a lambda |
Lambda bodies are restricted to a single expression. |
Use a regular function defined with def. |
| Forgetting to consume an iterator |
map(), filter(), and zip() do not immediately create lists. |
Use a loop, list(), or another suitable consumer. |
| Reusing an exhausted iterator |
The items have already been consumed. |
Create a new iterator when another pass is required. |
| Expecting zip() to include all extra items |
By default, zip() stops at the shortest iterable. |
Check lengths or use strict=True when equal lengths are required. |
| Using the wrong lambda parameters |
The function receives a different number of arguments than expected. |
Match the function signature to the number of iterables passed to map(). |
| Confusing map() and filter() |
Transformation and selection are different operations. |
Use map() to transform values and filter() to retain selected values. |
| Using lambda for complex logic |
Long expressions become difficult to read. |
Use a named function with a descriptive name. |
| Filtering out valid falsy values |
filter(None, iterable) removes all falsy items. |
Use an explicit predicate if values such as zero or an empty string must be retained. |
19. Best Practices
- Keep lambda functions short and easy to understand.
- Prefer named functions when logic requires multiple steps or needs documentation.
- Use built-in functions such as
int(), str(), and abs() directly with map() when suitable.
- Use
filter() with clear predicates that express the selection rule.
- Use
zip() to pair corresponding data instead of manually indexing multiple lists.
- Check that iterables have compatible lengths when every item must be matched.
- Remember that iterators are consumed as they are processed.
- Convert an iterator to a list only when you need to store, inspect, or reuse all the results.
- Prefer clear code over unnecessarily compact expressions.
- Test empty inputs, boundary values, and mismatched sequence lengths.
20. Practice Exercises
Exercise 1: Create a Lambda Function
Create a lambda function that accepts a number and returns its cube.
Expected result: Calling it with 3 should return 27.
Exercise 2: Use map() to Convert Temperatures
Given a list of Celsius temperatures, use map() and a lambda function to convert each temperature to Fahrenheit using the formula (celsius * 9 / 5) + 32.
Expected result: The input [0, 10, 20] should produce [32.0, 50.0, 68.0].
Exercise 3: Use filter() to Find Positive Numbers
Given the list [-10, 5, 0, 12, -3, 8], use filter() to retain only positive numbers.
Expected result: [5, 12, 8].
Exercise 4: Use zip() to Combine Data
Combine a list of employee names and salary amounts into tuples using zip().
Expected result: Each tuple should contain an employee name and the corresponding salary.
Exercise 5: Combine map() and filter()
Given a list of integers, first select numbers divisible by three and then use map() to calculate their squares.
Expected result: For [1, 3, 4, 6, 8, 9], the output should be [9, 36, 81].
Exercise 6: Product Revenue Calculator
Use zip() to combine product prices and quantities, then use map() to calculate revenue per product. Filter the results to retain products with revenue greater than 500.
21. Mini Project: Sales Data Analysis
Project objective: Process a small sales dataset using lambda functions, map(), filter(), and zip().
The project combines product names, unit prices, and quantities. It calculates revenue, filters high-revenue products, and creates a readable report.
products = ["Laptop", "Mouse", "Keyboard", "Monitor", "Webcam"]
prices = [55000, 800, 1500, 12000, 2500]
quantities = [2, 10, 4, 1, 6]
# Combine the related information.
sales_data = list(zip(products, prices, quantities))
# Calculate revenue for each product.
revenues = list(
map(
lambda item: (
item[0],
item[1],
item[2],
item[1] * item[2]
),
sales_data
)
)
# Select products generating revenue greater than 10000.
high_revenue = list(
filter(lambda item: item[3] > 10000, revenues)
)
print("All sales:")
for product, price, quantity, revenue in revenues:
print(product, "| Price:", price,
"| Quantity:", quantity,
"| Revenue:", revenue)
print("\\nHigh-revenue products:")
for item in high_revenue:
print(item[0], ":", item[3])
Expected output:
All sales:
Laptop | Price: 55000 | Quantity: 2 | Revenue: 110000
Mouse | Price: 800 | Quantity: 10 | Revenue: 8000
Keyboard | Price: 1500 | Quantity: 4 | Revenue: 6000
Monitor | Price: 12000 | Quantity: 1 | Revenue: 12000
Webcam | Price: 2500 | Quantity: 6 | Revenue: 15000
High-revenue products:
Laptop : 110000
Monitor : 12000
Webcam : 15000
Project tasks:
- Add a 10% discount for selected products using
map().
- Filter products with quantities below five.
- Calculate the total revenue using
sum().
- Sort the report by revenue using
sorted() and a key function.
- Handle input lists with mismatched lengths.
22. Interview Questions and Answers
Q1. What is a lambda function in Python?
A lambda function is an anonymous function defined using the lambda keyword. It can accept multiple parameters but is restricted to a single expression.
Q2. Can a lambda function accept multiple arguments?
Yes. For example, lambda a, b: a + b accepts two arguments and returns their sum.
Q3. Can a lambda function contain multiple statements?
No. A lambda body contains one expression. Use a regular function when multiple statements are needed.
Q4. What does map() do?
map() applies a function to items in one or more iterables and returns an iterator containing the results.
Q5. What does filter() do?
filter() returns an iterator containing items for which the supplied predicate evaluates to a truthy value.
Q6. What does zip() do?
zip() combines corresponding elements from multiple iterables into tuples.
Q7. What happens when zip() receives lists of different lengths?
By default, it stops when the shortest iterable is exhausted. With strict=True in Python 3.10 or later, a length mismatch raises ValueError.
Q8. Why do map(), filter(), and zip() return iterators?
They produce results lazily, allowing values to be processed as needed rather than creating a complete result collection immediately.
Q9. How can you convert a map object into a list?
Pass it to list(), such as list(map(lambda x: x * 2, [1, 2, 3])).
Q10. What is the difference between map() and filter()?
map() transforms each input item, while filter() selects which items to keep.
Q11. Can map() accept more than one iterable?
Yes. The supplied function must accept the corresponding number of arguments, and iteration stops when the shortest input iterable is exhausted.
Q12. Can lambda functions be used with sorted()?
Yes. A lambda function can be passed as the key argument to determine how elements are sorted.
students = [("Aarav", 85), ("Meera", 92), ("Kabir", 78)]
result = sorted(students, key=lambda student: student[1])
print(result)
Output:
[('Kabir', 78), ('Aarav', 85), ('Meera', 92)]
Q13. What happens when an iterator is consumed?
Once all its items have been consumed, iterating over the same iterator again produces no additional items. A new iterator must be created to process the source again.
Q14. When should you use a regular function instead of lambda?
Use a regular function when the operation is complex, needs multiple statements, benefits from a docstring, or should have a meaningful reusable name.
Q15. What is the difference between zip() and map() with multiple iterables?
zip() groups corresponding elements into tuples. map() passes corresponding elements to a function and yields the function's results.
23. Quick Revision Checklist
- Lambda functions are created using
lambda parameters: expression.
- A lambda function automatically returns the value of its expression.
map() transforms items in one or more iterables.
filter() selects items based on a predicate.
zip() combines corresponding items into tuples.
list() can convert an iterator into a list.
- Iterators are lazy and normally consumed during iteration.
- By default,
zip() stops at the shortest iterable.
zip(strict=True) checks for equal iterable lengths in Python 3.10 and later.
- List comprehensions can be a readable alternative to
map() and filter().
- Use named functions for complex logic.
- Practice combining these tools with real-world datasets.
24. Conclusion
Lambda functions, map(), filter(), and zip() are useful Python tools for concise and efficient data processing. Lambda functions provide short expressions that can act as functions, map() transforms data, filter() selects matching items, and zip() brings related data together.
Understanding how these tools work individually and together helps you write clearer programs for data transformation, validation, reporting, and automation. Practice them with lists of numbers, student records, product inventories, and sales datasets. Choose the approach that makes the code easiest to understand and maintain.
Continue learning: Explore the Python Training Course, register for a course demo, or visit the JustAcademy website for more learning resources.