</> Code Editor { } Code Formatter

Python Map, Filter, and Reduce Exercises


1/18

Python Map, Filter, and Reduce Practice Questions

Correct
0%

Which of the following statements about Python’s map(), filter(), and reduce() is correct?


This exercise tests your conceptual understanding of Python's map, filter, and reduce functions.

  • Option 1: Incorrect. In Python 3, map() returns an iterator, not a list directly. You need to use list(map(...)) to get a list.
  • Option 2: Incorrect. filter() may return fewer elements than the original iterable because it only keeps elements satisfying the condition.
  • Option 3: Correct. reduce() (from functools) applies a function cumulatively to elements, producing a single aggregated result.
  • Option 4: Incorrect. map() can work with any iterable, including lists, tuples, and sets.

Key Takeaways:

  • map() – applies a function to each element of any iterable.
  • filter() – selects elements based on a condition.
  • reduce() – reduces an iterable to a single cumulative value.

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

FunctionPurposeReturnsExample Use Case
map()Transform each elementMap object (convert to list)Convert temperatures from Celsius to Fahrenheit
filter()Select elements based on conditionFilter object (convert to list)Get even numbers from a list
reduce()Combine elements cumulativelySingle valueCalculate 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]

Map with multiple iterables:

nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
summed = list(map(lambda x, y: x + y, nums1, nums2))
print(summed)  # Output: [5, 7, 9]

Filter Function

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


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!