Reduce applies a function cumulatively to elements of a list.
Lambda must take exactly two arguments.
You have a list of temperatures in Celsius: [0, 20, 30, 100]. Which code snippet converts all temperatures to Fahrenheit using map and lambda?
This exercise applies map() with a lambda function to a real-world scenario.
Option 1: Correct. Formula for Celsius to Fahrenheit: F = C*9/5 + 32.
Option 2: Incorrect. Multiplying by 2 is wrong, not the proper formula.
Option 3: Incorrect. Returns a map object, not a list, so result isn’t visible directly.
Option 4: Incorrect. Simply adding 32 is incorrect for Fahrenheit conversion.
Key Takeaways:
Always check the formula in real-world mapping scenarios.
Remember to wrap map() with list() to see results in Python 3.
You have a list of numbers: [3, 6, 2, 9, 1]. You want to create a new list where:
Add 10 if the number is greater than 5
Subtract 2 if the number is 5 or less
Which of the following correctly implements this using map() and lambda?
This exercise focuses on using map() with a conditional lambda for element-wise transformations.
Option 1: Correct. Adds 10 if x>5 (6 and 9) and subtracts 2 if x≤5 (3, 2, 1), giving the correct new list.
Option 2: Incorrect. Uses x>=5, so 5 would also get +10. Since there is no 5 in the list, the effect is subtle but shows misunderstanding of inequality usage.
Option 3: Incorrect. Adds 2 instead of subtracting 2 for numbers ≤5, giving wrong results.
Option 4: Incorrect. Subtracts 10 from numbers >5 instead of adding 10, producing wrong results.
Key Takeaways:
Conditional logic inside lambda uses the syntax: value_if_true if condition else value_if_false.
Be careful with inequality signs (>, >=, <) as they affect which elements meet the condition.
Always wrap map() in list() to get a visible list in Python 3.
You have a list of numbers: [1, 2, 3, 4, 5, 6]. You want to filter all numbers greater than 3. Which of the following code snippets will correctly produce the filtered list?
This exercise tests understanding of filter() and subtle differences in what the lambda returns.
Option 1: Incorrect. Works in most cases, but directly returning the condition may cause confusion if the lambda logic is combined with more complex expressions. It is correct technically but less explicit than using bool().
Option 2: Incorrect. Returns 0 for numbers ≤3. Filter treats 0 as False, so these elements are excluded, but using 0 like this is confusing and not best practice. Can cause bugs in nested expressions.
Option 3: Incorrect. Uses map() instead of filter(), so it returns a list of boolean values: [False, False, False, True, True, True], not the actual numbers.
Option 4: Correct. Using bool(x>3) ensures the lambda returns a proper boolean, making filter behavior explicit. This is the cleanest and safest way.
Key Takeaways:
Filter expects the lambda to return a truthy/falsy value. Returning integers directly (like in Option 2) works, but is risky in complex scenarios.
Using bool(condition) makes your intent explicit.
Map returns transformed elements; filter selects elements. Confusing the two is a common mistake.
You have a list of numbers: [1, 2, 3, 4, 5]. You want to create a new list with each number squared. Which of the following code snippets correctly produces the same result and is most efficient and readable in Python 3?
This exercise tests understanding of map + lambda vs list comprehensions and their readability/efficiency.
Option 1: Works correctly. Uses map() with lambda to square numbers. However, it is slightly less readable for beginners compared to list comprehension.
Option 2: Correct. List comprehension is concise, readable, and Pythonic. Produces the same squared numbers efficiently.
Option 3: Incorrect. Lambda multiplies by 2 instead of squaring, producing the wrong results.
Option 4: Works, but unnecessarily adds a condition if x>0. Though the result is the same here, it introduces extra complexity and is less general.
Key Takeaways:
List comprehensions are usually more readable and Pythonic for simple transformations.
Map + lambda is useful for applying an existing function or when readability is not a priority.
Always check that the lambda performs the intended operation (x**2 vs x*2).
You have a list of employees, each represented as a dictionary:
You want to get the names of employees earning more than 4000 using filter() and map().
Which of the following snippets does this correctly?
This exercise combines map() and filter() in a real-world scenario, testing the correct order of operations.
Option 1: Correct. First, filter() selects employees with salary >4000, then map() extracts their names. Produces ['Bob', 'Charlie', 'Eva'].
Option 2: Incorrect. Applies map() first, which converts employees to names (strings). Then filter() tries to access e['salary'] on a string, causing a TypeError.
Option 3: Incorrect. Uses >= instead of >. While this may produce similar output here, it subtly changes the boundary logic and could introduce off-by-one errors in other datasets.
Option 4: Incorrect. Using bool() here is redundant; still correct logically, but less readable and overcomplicates the lambda.
Key Takeaways:
The order of filter() and map() is crucial: filter first, then map.
Nested lambdas can be tricky; always consider what each function returns.
Prefer clear and readable expressions in real-world pipelines.
You have a list of products, each represented as a dictionary:
You want to apply a 10% discount only on products priced above $100 and get a list of discounted prices. Which of the following code snippets does this correctly?
Option 1: Correct. Uses a conditional inside map() to apply a 10% discount only to products with price >100, while keeping other prices unchanged. Produces: [1080.0, 25, 75, 270.0, 10].
Option 2: Incorrect. Filters products >100 first, then maps discounted prices. Products ≤100 are excluded from the final list, which is incorrect.
Option 3: Incorrect. Maps all prices first, then filters >100. After mapping, all prices are discounted or modified, so the filter may produce wrong results. The logic does not match the requirement.
Option 4: Incorrect. While logically equivalent to Option 1, using bool() is redundant and less readable. Option 1 is preferred as clean Pythonic code.
Key Takeaways:
Conditional logic inside map() is often more practical than combining map + filter in multi-step operations.
Order matters: filtering before mapping or vice versa can change the final results.
Keep code readable and avoid unnecessary constructs like bool() when the condition already returns True/False.
You want to give a $500 bonus only to employees earning more than $4000 and then calculate the total of all updated salaries. Complete the code below using filter(), map(), and reduce():
Which of the following correctly fills the blanks?
This exercise tests a multi-step pipeline combining filter(), map(), and reduce() in a real-world scenario.
Option 1: Incorrect. Applies the bonus only to filtered employees, but does not account for unfiltered employees. Total sum will miss salaries ≤4000.
Option 2: Incorrect. Similar issue, includes salaries exactly 4000, which may not match requirement depending on strict > condition.
Option 3: Incorrect. Does not add the bonus; totals only the filtered salaries without the increment.
Option 4: Correct. The lambda in map() conditionally adds 500 only for employees with salary >4000, while others remain unchanged. The filter ensures only relevant employees are processed. This produces the correct total sum.
Key Takeaways:
Using map() with a conditional allows multi-step transformations in a single line.
Filter determines which elements are processed; map applies transformations.
Reduce aggregates values. Understanding the flow (filter → map → reduce) is crucial.
You have a list of dictionaries representing product sales for a week:
You want to calculate the total revenue only from products with total value > 50 (total value = units × price). Which code snippet correctly does this using map(), filter(), and reduce()?
This exercise tests nested functional programming with map(), filter(), and reduce() in a real-world scenario.
Option 1: Correct. Filters products with total value >50, maps to total value, then reduces by summing: (5*20=100, 2*100=200, 1*200=200) → total = 100+200+200=500.
Option 2: Incorrect. Mapping first produces values for all products, then filtering tries to filter numeric values as if they were dictionaries. Causes a TypeError.
Option 3: Incorrect. Uses multiplication in reduce, which gives wrong total revenue.
Option 4: Incorrect. Uses >= instead of >, which changes boundary logic subtly. While sum() works, it does not test reduce usage explicitly for the exercise.
Key Takeaways:
Order of filter() and map() matters.
Reduce should be applied correctly depending on aggregation required (sum vs product).
Practical scenarios often require combining multiple functional steps carefully.
A company wants to give a 10% bonus only to employees earning above $4000 and then calculate the total payroll.
From a design perspective, which of the following functional pipelines correctly achieves this using map(), filter(), and reduce()?
This exercise is conceptual and tests understanding of functional pipelines and proper ordering of operations.
Option 1: Incorrect. Uses sum over all employees, not filtering anyone. Applies bonus to everyone, violating requirement.
Option 2: Incorrect. Mapping first, then filtering, is wrong. After mapping, filter() tries to access e['salary'] on a numeric value, causing TypeError.
Option 3: Correct.
filter() selects employees earning more than $4000.
map() applies a 10% bonus only to the filtered employees.
reduce() sums the updated salaries to compute total payroll.
Option 4: Incorrect. Filters using >=4000 and maps only salaries, not adding the bonus. Totals without bonus are wrong.
Key Takeaways:
Conceptual understanding: In multi-step functional pipelines, order of filter() and map() matters critically.
Reduce aggregates the final processed values; make sure transformation logic matches requirements.
Even minor differences (>= vs >, including bonus calculation) can change results subtly.
A developer wrote the following code to calculate the total revenue from products priced above $50:
The code throws an error or gives unexpected results. Which fix is correct?
This exercise tests your ability to spot **functional pipeline mistakes** in Python.
Original Problem: The code applies filter() after map(). After mapping, the items are numeric values (price*units). Filter then tries to access p['price'] on a number, causing a TypeError.
Option 1: Incorrect. Filtering the dictionaries without mapping first will keep products, but the reduce function still expects numeric values, so reduce will fail.
Option 2: Correct. First, filter products with price >50, then map to calculate revenue (price*units). Finally, reduce sums numeric values. This ensures proper order and correct total revenue.
Option 3: Incorrect. Using sum() alone won’t fix the pipeline error; the map-filter order issue remains.
Option 4: Incorrect. Mapping only price loses the units multiplication, producing wrong total revenue.
Key Takeaways:
Order matters: filter() should operate on dictionaries, map() converts to numeric values before aggregation.
Errors in functional pipelines often occur due to **type mismatches** after map or filter.
Debugging requires reasoning about **what each function outputs** and how it flows to the next function.
A developer wants to compute the total revenue from products with price > 50. They consider two approaches:
total = sum([p['price']*p['units'] for p in products if p['price'] > 50])
Question: Which statement best describes the difference between the two approaches?
This exercise is conceptual, comparing two ways to achieve the same goal using Python.
Option 1: Incorrect. reduce() is not inherently faster than sum(); performance depends on implementation and readability is more important for maintainable code.
Option 2: Correct. Approach B (list comprehension + sum) is generally more readable and Pythonic. Approach A uses filter(), map(), and reduce() to illustrate functional programming but is less intuitive for beginners.
Option 3: Incorrect. Both approaches produce the same total revenue if implemented correctly.
Option 4: Incorrect. List comprehensions are efficient in Python; functional pipelines do not guarantee better performance.
Key Takeaways:
Functional programming constructs like map(), filter(), reduce() are conceptually useful but may reduce readability for simple tasks.
List comprehensions + built-in functions like sum() often provide more readable and maintainable code.
Always consider readability and maintainability, especially in team projects, alongside correctness and performance.
You have an inventory list with products and their stock:
They claim the code is correct, but they receive unexpected results when adding more orders. Which fix correctly resolves potential issues?
This exercise focuses on identifying a more robust and readable solution for a functional pipeline calculation.
Option 1: Incorrect. Changing > to >= only alters the boundary condition slightly, does not fix robustness or readability.
Option 2: Correct. Using a list comprehension with sum() is more readable, avoids potential issues with lazy evaluation in some Python versions, and directly calculates total discount for orders above 100.
Option 3: Incorrect. Using multiplication in reduce changes logic entirely; total discount would be nonsensical.
Option 4: Incorrect. Mapping only the amount ignores the 10% discount requirement; produces wrong total.
Key Takeaways:
Functional pipelines using map(), filter(), reduce() are powerful but can be less readable for multi-step financial calculations.
List comprehensions with built-in functions like sum() often provide a simpler, more maintainable alternative.
Always verify the output after adding more data; subtle issues may arise from lazy evaluation or incorrect transformations.
Quick Recap of Python Map, Filter, and Reduce Concepts
If you are not clear on the concepts of Map, Filter, and Reduce, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
Python Map, Filter, and Reduce — Overview
map(), filter(), and reduce() are built-in Python tools for functional programming. They allow you to process iterables efficiently without writing explicit loops.
Key points:
map() transforms each item in an iterable
filter() selects items based on a condition
reduce() cumulatively reduces items to a single value (requires functools)
Often used with lambda functions for concise code
Comparison Table: Map vs Filter vs Reduce
Function
Purpose
Returns
Example Use Case
map()
Transform each element
Map object (convert to list)
Convert temperatures from Celsius to Fahrenheit
filter()
Select elements based on condition
Filter object (convert to list)
Get even numbers from a list
reduce()
Combine elements cumulatively
Single value
Calculate sum or product of numbers
Map Function
map() applies a function to each element of an iterable and returns a map object.
Syntax:
map(function, iterable)
Examples:
# Using map with a regular function
def square(x):
return x ** 2
numbers = [1, 2, 3, 4]
squared = list(map(square, numbers))
print(squared) # Output: [1, 4, 9, 16]
# Using map with lambda
numbers = [5, 6, 7, 8]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [25, 36, 49, 64]
filter() selects elements from an iterable that satisfy a condition.
Syntax:
filter(function, iterable)
Examples:
# Using filter with a regular function
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(is_even, numbers))
print(even_numbers) # Output: [2, 4, 6]
# Using filter with lambda
numbers = [7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [8, 10]
Reduce Function
reduce() applies a function cumulatively to reduce a sequence to a single value. It is available in the functools module.
Syntax:
from functools import reduce
reduce(function, iterable[, initializer])
Examples:
from functools import reduce
# Sum of all numbers
numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 10
# Product of all numbers
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
# Using initializer
numbers = [1, 2, 3]
total = reduce(lambda x, y: x + y, numbers, 10)
print(total) # Output: 16
Practical Use Cases
# Map: Convert temperatures from Celsius to Fahrenheit
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit) # Output: [32.0, 68.0, 98.6, 212.0]
# Filter: Get words longer than 3 letters
words = ["sun", "moon", "star", "sky"]
long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words) # Output: ['moon', 'star']
# Reduce: Find the maximum number
from functools import reduce
numbers = [5, 10, 2, 8]
max_num = reduce(lambda x, y: x if x > y else y, numbers)
print(max_num) # Output: 10
Best Practices
Use lambda functions for simple operations with map, filter, or reduce
Avoid complex logic inside lambda; prefer named functions if needed
Convert map and filter objects to list() for readability
Use reduce carefully, especially for large lists, as it can reduce readability compared to explicit loops
Use meaningful variable names to maintain code clarity
Test intermediate results to avoid unexpected outputs
# Example: Best practice with map and lambda
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
# Example: Avoid complex lambda
# Instead of: reduce(lambda x, y: x*y if x>0 else y, numbers)
# Use a named function for clarity
from functools import reduce
def multiply_positive(x, y):
return x * y if x > 0 else y
product = reduce(multiply_positive, numbers)
print(product)
Summary: Key Points About Map, Filter, and Reduce
map(): Transforms each element in an iterable
filter(): Selects elements that meet a condition
reduce(): Combines elements cumulatively into a single result
Frequently used with lambda functions for concise code
Useful for data processing, functional programming, and avoiding explicit loops
Following best practices ensures readable, maintainable code
Test Your Python Map, Filter, and Reduce Knowledge
Practicing Python Map, Filter, and Reduce? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python – Map, Filter, and Reduce
Welcome to Solviyo’s Python – Map, Filter, and Reduce exercises, a practical collection designed to help learners work efficiently with Python’s functional programming tools. In this section, we focus on using map, filter, and reduce to process collections, transform data, and simplify complex operations. These exercises come with clear explanations and answers so you can learn confidently and understand every concept step by step.
What You Will Learn
Through these exercises, you will explore how map, filter, and reduce help you write concise and readable Python code, including:
Understanding what map does and how to apply a function to each item in an iterable efficiently.
Using filter to extract elements that meet specific conditions from lists or other iterables.
Applying reduce from the functools module to combine elements of a collection into a single value.
Combining lambda functions with map, filter, and reduce for concise one-liners and practical data transformations.
Recognizing best practices for functional programming patterns in Python and avoiding common pitfalls.
Working through hands-on exercises with explanations and answers to strengthen your understanding of functional operations.
These exercises are designed to be approachable but practical, helping you understand not just how map, filter, and reduce work, but why they are useful tools for efficient Python programming. A Quick Recap section is also available for refreshing key concepts before practicing.
Why Learning Map, Filter, and Reduce Matters
Map, filter, and reduce are essential tools for anyone looking to write clean, functional-style Python code. They simplify tasks that would otherwise require lengthy loops and conditional statements. By practicing these exercises with MCQs, explanations, and answers, you will gain confidence in processing collections, transforming data, and building more efficient programs. Mastery of these tools is especially valuable for coding interviews, data processing tasks, and real-world Python projects.
Start Strengthening Your Python Skills
With Solviyo’s Map, Filter, and Reduce exercises, you can start practicing immediately through practical tasks and MCQs. Each exercise includes explanations and answers, so you can verify your understanding as you progress. Regular practice will help you integrate these functional tools into your Python coding skillset, making your programs cleaner, more readable, and highly efficient. Dive in and enhance your Python programming abilities step by step!
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.