Skip to content

Python map() Function

How to use Python's map() function to apply operations to each element in iterables like lists and tuples, with practical examples including squares, cubes, and string conversions.

The map() function executes a given function to each element of an iterable (such as lists, tuples, etc.).

Syntax

map(function, iterables)

map() Parameters

Python map() function parameters:

Parameter Condition Description
function Required A function to which map passes each element of the given iterable.
iterable Required An iterable which is to be mapped. You can pass one or more iterables.

map() Return Value

Python map() function returns a map object, which can be easily converted to lists, tuples, etc.

Examples

Example 1: Compute Square Numbers with map() function

Let's use the map() function to calculate the square of a list of numbers:

def square(number):
    return number * number

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

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

output

[1,  4,  9,  16]

Example 2: Compute Cube Numbers with map() function

Let's use the map() function to calculate the cube of a list of numbers:

def cube(num):
    return num**3

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

new_list = list(map(cube, my_list))
print(new_list)  # Output: [1,  8,  27,  64,  125]

output

[1,  4,  9,  16]

Example 3: Converting Strings to Integers with map() function

Let's convert a list of string numbers to a list of numbers using the map() function

str_nums = ["4", "8", "6", "5", "3", "2", "8", "9", "2", "5"]

int_nums = map(int, str_nums)

result = list(int_nums)
print(result)  # Output: [4,  8,  6,  5,  3,  2,  8,  9,  2,  5]

output

[4,  8,  6,  5,  3,  2,  8,  9,  2,  5]

Example 4: String Modification using map() function

map() function can be used to modify strings.

For example, convert each string in the list into a list of individual characters:

languages=['Python', 'Java','Rust']
result= list(map(list, languages))
print(result)

output

[['P', 'y', 't', 'h', 'o', 'n'], ['J', 'a', 'v', 'a'], ['R', 'u', 's', 't']]

Example 5: map() function and Lambdas

In a map() function, we can also use a lambda function instead of a regular function. For example:

numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)

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

output

[1, 4, 9, 16]

Example 6: Add Multiple Lists using map() and lambda

num1 = [1, 2, 3]
num2 = [10, 20, 30]
num3 = [100, 200, 300, 400, 500]

result1 = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result1)) # Output: [11, 22, 33]
result2 = map(lambda n1, n2: n1+n2, num1, num3)
print(list(result2)) # Output: 

output

[11, 22, 33]
[101, 202, 303]
Navigation