Table of Contents

    map()

    CHAPTER 29.5 · ADVANCED PYTHON FEATURES

    map() in Python

    Learn how to apply the same function to every value of one or more Python iterables.

    Python programs frequently need to perform the same operation on every item in a collection. For example, a program may calculate squares, convert strings to uppercase, clean text, or apply a discount to every price.

    The built-in map() function applies a function to values obtained from one or more iterables. It returns a map object that produces transformed values during iteration.

    Learning objective: Learn the syntax of map(), use named and built-in functions, process multiple iterables, and convert map results into collections.

    Prerequisites

    What You Should Know

    • Python lists, tuples, and strings
    • Writing and calling functions
    • Function parameters and return values
    • Using for loops
    • Basic knowledge of lambda expressions
    • Basic understanding of iterables

    What is map()?

    map() is a built-in Python function that applies a specified function to every value supplied by an iterable.

    When multiple iterables are supplied, the function receives one corresponding value from each iterable during every iteration.

    Think of map() as a transformation machine

    Every input value enters the machine, the supplied function processes it, and a transformed result is produced.

    Syntax

    MAP SYNTAX
    map(function, iterable, ...)
    map(function, iterable)
    Argument Purpose
    function Defines the transformation applied to each value.
    iterable Supplies values to the function.
    Additional iterables Supply additional corresponding function arguments.

    Basic Example

    def calculate_square(number):
        return number ** 2
    
    
    numbers = [1, 2, 3, 4, 5]
    
    squares = map(
        calculate_square,
        numbers
    )
    
    print(list(squares))

    Output:

    [1, 4, 9, 16, 25]

    The calculate_square() function is applied to every number in the list.

    What Does map() Return?

    numbers = [1, 2, 3]
    
    result = map(
        str,
        numbers
    )
    
    print(type(result))

    Output:

    <class 'map'>
    map() returns a map object. Convert it with list() when a list is required.

    Use a Built-in Function

    Convert numeric strings into integers:

    text_values = [
        "10",
        "25",
        "40"
    ]
    
    numbers = list(
        map(
            int,
            text_values
        )
    )
    
    print(numbers)

    Output:

    [10, 25, 40]

    Transform Strings

    names = [
        "amina",
        "rahul",
        "david"
    ]
    
    uppercase_names = list(
        map(
            str.upper,
            names
        )
    )
    
    print(uppercase_names)

    Output:

    ['AMINA', 'RAHUL', 'DAVID']

    Use map() with lambda

    numbers = [
        1,
        2,
        3,
        4
    ]
    
    cubes = list(
        map(
            lambda number: number ** 3,
            numbers
        )
    )
    
    print(cubes)

    Output:

    [1, 8, 27, 64]
    Use lambda only for short transformations. Use a named function when the logic is complex or reusable.

    Process Multiple Iterables

    def add_numbers(
        first_number,
        second_number
    ):
        return first_number + second_number
    
    
    first_numbers = [10, 20, 30]
    second_numbers = [1, 2, 3]
    
    results = list(
        map(
            add_numbers,
            first_numbers,
            second_numbers
        )
    )
    
    print(results)

    Output:

    [11, 22, 33]

    The function accepts two parameters because two iterables are supplied to map().

    Calculate Line Totals

    quantities = [2, 5, 3]
    unit_prices = [100, 250, 400]
    
    line_totals = list(
        map(
            lambda quantity, price:
                quantity * price,
            quantities,
            unit_prices
        )
    )
    
    print(line_totals)

    Output:

    [200, 1250, 1200]

    Iterables with Different Lengths

    When multiple iterables are supplied, processing stops when the shortest iterable is exhausted.

    first_numbers = [
        10,
        20,
        30
    ]
    
    second_numbers = [
        1,
        2
    ]
    
    results = list(
        map(
            lambda first, second:
                first + second,
            first_numbers,
            second_numbers
        )
    )
    
    print(results)

    Output:

    [11, 22]
    Important Validate collection lengths when every value must have a corresponding match.

    map Object Exhaustion

    numbers = [1, 2, 3]
    
    squares = map(
        lambda number: number ** 2,
        numbers
    )
    
    print(list(squares))
    print(list(squares))

    Output:

    [1, 4, 9]
    []

    The first conversion consumes the map object. Create a new map object when the transformation must be processed again.

    map() vs List Comprehension

    Using map()

    squares = list(
        map(
            calculate_square,
            numbers
        )
    )

    Using List Comprehension

    squares = [
        number ** 2
        for number in numbers
    ]

    Prefer map()

    • An existing function performs the transformation
    • Several iterables supply function arguments
    • The result will be consumed during iteration

    Prefer List Comprehension

    • The transformation is a short expression
    • Filtering is also required
    • A list is immediately required

    Handle Invalid Values

    def convert_to_integer(value):
        try:
            return int(value)
        except ValueError:
            return None
    
    
    values = [
        "10",
        "invalid",
        "40"
    ]
    
    converted_values = list(
        map(
            convert_to_integer,
            values
        )
    )
    
    print(converted_values)

    Output:

    [10, None, 40]

    Common Mistakes

    1

    Calling the Function

    Incorrect map(calculate_square(), numbers)
    Correct map(calculate_square, numbers)
    2

    Expecting a List

    map() returns a map object.

    Solution Convert it using list() when necessary.
    3

    Incorrect Function Parameters

    The function must accept one parameter for every supplied iterable.

    4

    Reusing a Consumed map Object

    A map object is consumed during iteration.

    Solution Create a new map object or store its results in a collection.

    Best Practices

    Recommended Practices

    • Pass a function object without calling it.
    • Use named functions for reusable transformations.
    • Use lambda only for short expressions.
    • Validate lengths when processing multiple iterables.
    • Convert to a list only when values must be stored.
    • Prefer list comprehension when it produces clearer code.
    • Avoid unnecessary side effects in mapping functions.

    Knowledge Check

    1

    What does map() return?

    It returns a map object that produces transformed values during iteration.

    2

    How do you convert it to a list?

    result = list(
        map(
            function,
            iterable
        )
    )
    3

    Can map() process multiple iterables?

    Yes. The function must accept one corresponding argument from every supplied iterable.

    map() Quick Reference

    # Apply a named function
    result = map(
        function,
        iterable
    )
    
    # Convert to a list
    result = list(
        map(
            function,
            iterable
        )
    )
    
    # Use lambda
    result = list(
        map(
            lambda item: transform(item),
            iterable
        )
    )
    
    # Process two iterables
    result = list(
        map(
            function,
            first_iterable,
            second_iterable
        )
    )
    
    # Iterate over results
    for value in map(
        function,
        iterable
    ):
        print(value)

    Summary

    What You Learned

    • map() applies a function to iterable values.
    • It returns a map object rather than a list.
    • Named, built-in, and lambda functions can be used.
    • Multiple iterables can supply corresponding arguments.
    • Processing stops when the shortest iterable is exhausted.
    • A map object is consumed during iteration.
    • List comprehension may be clearer for simple expressions.

    Key Takeaway

    Use map() when the same function must transform values from one or more iterables. Use named functions for complex logic and list comprehension when the inline expression is clearer.