Python map() Function Explained

The Python map() function is a powerful built-in function that applies a function to every element in one or more iterables. It allows for cleaner, more efficient code, eliminating the need for explicit loops.

This guide will break down how the map() function works with practical examples and step-by-step explanations.


Syntax

map(function, iterable, [iterable1, iterable2, ...])

Parameters

  • function (Required): The function to be applied to each element in the iterable.
  • iterable (Required): One or more iterables whose elements are passed to the function.

Return Value

The map() function returns a map object, which is an iterator.

Convert it to a list or tuple for viewing results.


Let’s explore the map() function with a step-by-step breakdown using an example where we want to square each number in a list.

Example – Square Each Number in a List

def square(num):
    return num ** 2

numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)

print(list(squared_numbers))  # Output: [1, 4, 9, 16]

1) Defining the Function

In this example, we define a square() function that takes a number and returns its square.

2) Applying map()

We then apply the map() function, passing in the square function and the numbers list. The map() function applies square() to each element of the numbers list.

3) Converting the Result

Since map() returns a map object (iterator), we use list() to convert it into a list, which produces [1, 4, 9, 16].


Using map() with Multiple Iterables

You can process multiple iterables at once with map(). Let’s see an example that adds corresponding elements from two lists.

# def add(x, y):
#     return x + y

list1 = [1, 2, 3]
list2 = [10, 20, 30]

result = list(map(lambda x, y: x + y, list1, list2))
print(result)  # Output: [11, 22, 33]

In this case, map() applies the lambda function to pairs of elements from list1 and list2, producing the sum of corresponding items.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *