Map in Python

Python : Map

What is Map in Python?

Map is a built-in Python function that allows you to apply a function to each element of an iterable object such as a list, tuple, or dictionary. It returns a new iterable object with the modified values.

In simple words, map() function allows you to take an iterable object and apply a function to all the elements of that object.

Map Syntax in Python:

map(function, iterable)

Map Parameters:

  • function: The function that you want to apply to the elements of the iterable.
  • iterable: The iterable object (e.g. list, tuple, dictionary, etc.) that you want to apply the function to.
  • Return value: The map() function returns a map object, which is an iterator that yields the results of applying the function to each element of the iterable in sequence.

Map function use in Python

  1. Using map() with a function

    Suppose we want to create a list of squares of numbers from 1 to 5. We can use the map() function to apply a function that returns the square of a number to each element of a list containing the numbers from 1 to 5.

    def square(x):
        return x**2
    
    numbers = [1, 2, 3, 4, 5]
    squares = map(square, numbers)
    
    print(list(squares))
    # Output: [1, 4, 9, 16, 25]
    
  2. Using map() with lambda function

    We can use a lambda function with map() to create the same list of squares as in the previous example.

    numbers = [1, 2, 3, 4, 5]
    squares = map(lambda x: x**2, numbers)
    
    print(list(squares))
    Output: [1, 4, 9, 16, 25]
    
  3. Using map() with multiple iterables

    We can also use map() with multiple iterables. In this example, we want to add corresponding elements of two lists.

    list1 = [1, 2, 3, 4]
    list2 = [10, 20, 30, 40]
    
    result = map(lambda x, y: x + y, list1, list2)
    
    print(list(result))
    # Output: [11, 22, 33, 44]
    
  4. Using map() with dictionaries

    We can use map() with [dictionaries]((https://learngolangonline.com/python/dictionaries) to apply a function to the values of a dictionary.

    prices = {'apple': 0.5, 'banana': 0.25, 'orange': 0.75}
    
    result = map(lambda x: round(x * 1.1, 2), prices.values())
    
    print(list(result))
    # Output: [0.55, 0.28, 0.83]
    
  • Map() is a powerful function in Python that allows you to apply a function to all the elements of an iterable object.
  • It can be used with simple functions as well as with lambda functions.
  • Map() can also be used with multiple iterables and dictionaries.

Filter in Python

Reduce in Python

Sets in Python