Python’s map() Function

Learn Python @ Freshers.in

Python’s map() function is a powerful tool for applying a function to all elements of an iterable. In this comprehensive guide, we’ll delve into the intricacies of map(), covering its syntax, applications, and practical examples to help you harness its full potential in Python programming.

Understanding map() Function:

The map() function in Python is used to apply a specified function to each item of an iterable (like a list or tuple) and return an iterator. Its syntax is straightforward:

map(function, iterable)
  • function: The function to apply to each item of the iterable.
  • iterable: The iterable (such as a list or tuple) to be mapped.

Example 1: Basic Usage

Let’s start with a simple example:

# Define a function to square a number
def square(x):
    return x ** 2

# Apply the function to each element of a list
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers))  # Output: [1, 4, 9, 16, 25]

Here, we define a function square() that squares a number. We then use map() to apply this function to each element of the list numbers, resulting in a new list squared_numbers.

Example 2: Using Lambda Functions

You can also use lambda functions with map():

# Use lambda function to double each element of a list
numbers = [1, 2, 3, 4, 5]
doubled_numbers = map(lambda x: x * 2, numbers)
print(list(doubled_numbers))  # Output: [2, 4, 6, 8, 10]

In this example, we use a lambda function to double each element of the list numbers.

Example 3: Applying map() to Multiple Iterables

map() can also be applied to multiple iterables:

# Add corresponding elements of two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sums = map(lambda x, y: x + y, list1, list2)
print(list(sums))  # Output: [5, 7, 9]

Here, we use map() with a lambda function to add corresponding elements of two lists list1 and list2.

Example 4: Handling Uneven Length Iterables

map() stops when the shortest iterable is exhausted:

list1 = [1, 2, 3]
list2 = [4, 5]
sums = map(lambda x, y: x + y, list1, list2)
print(list(sums))  # Output: [5, 7]

In this case, since list2 is shorter, map() stops after adding the first two elements of list1 and list2.

Author: user