Python Map Function

In this tutorial, you will learn about Map Function in Python

 

Introduction


In Python, the map() function is a built-in function that applies a specified function to all items in an iterable (e.g., a list) and returns an iterator that produces the results.

The map() function is particularly useful when you need to perform a specific operation on each element of a collection without using explicit loops.

 

Syntax


The syntax for the map() function is as follows:

map(function, iterable, ...)

function: The function to apply to each item in the iterable.

iterable: The iterable (e.g., list, tuple) whose elements will be processed by the function.

 

Basic Examples


Let's explore some basic examples to understand how the map() function works.

Example 1: Square each element in a list

numbers = [1, 2, 3, 4, 5]

squared_numbers = map(lambda x: x ** 2, numbers)

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


In this example, the map() function applies the lambda function to each element of the numbers list, producing a new iterable with the squared values.

Example 2: Convert temperatures from Celsius to Fahrenheit

temperatures_celsius = [0, 25, 37, 100]
to_fahrenheit = lambda c: (c * 9/5) + 32

temperatures_fahrenheit = map(to_fahrenheit, temperatures_celsius)
print(list(temperatures_fahrenheit))
# Output: [32.0, 77.0, 98.6, 212.0]


Here, the map() function is used to convert temperatures from Celsius to Fahrenheit using the provided lambda function.

 

Combining map() with Multiple Iterables


The map() function can accept multiple iterables, and the provided function should have as many parameters as there are iterables.

Example: Add corresponding elements from two lists

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

In this case, the map() function takes two lists and a lambda function with two parameters to add corresponding elements.

 

Using map() with Functions


The map() function can also be used with built-in functions or functions defined using def.

Example: Convert a list of strings to integers

numbers_as_strings = ["1", "2", "3", "4"]
convert_to_int = map(int, numbers_as_strings)
print(list(convert_to_int))  # Output: [1, 2, 3, 4]


Here, the map() function applies the built-in int() function to convert each string in the list to an integer.

 

Summary


The map() function is a powerful tool in Python for applying a specified function to each element of an iterable. It simplifies the process of transforming data in a concise and readable manner. While map() is a versatile function, it's essential to consider the use of list comprehension and other alternatives, depending on the specific use case and readability requirements.
 

© 2022-2023 All rights reserved.