Python map() function

Definition and Usage

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

Python map() function

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Syntax:

map(fun, iter)

Parameter

  • fun :ย It is a function to which map passes each element of given iterable.
  • iter :ย It is a iterable which is to be mapped.

NOTE :ย You can pass one or more iterable to the map() function.

Returns :

Returns a list of the results after applying the given function  
to each item of a given iterable (list, tuple etc.)

NOTE : The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) .

Example 1:

# Double all numbers using map and lambda 

numbers = (2, 4, 6, 8)
result = map(lambda x: x + x, numbers)
print(list(result))

Output:

[4, 8, 12, 16]

Example 2:

# List of strings 
l = [โ€˜wikitechyโ€™, โ€˜wikiโ€™]

# map() can listify the list of strings individually
test = list(map(list, l))
print(test)

Output:

[[โ€˜wโ€™, โ€˜iโ€™, โ€˜kโ€™, โ€˜iโ€™, โ€˜tโ€™, โ€˜eโ€™, โ€˜cโ€™, โ€˜kโ€™, โ€˜yโ€™], [โ€˜wโ€™, โ€˜iโ€™, โ€˜kโ€™, โ€˜iโ€™]]

Example 3:

# Python program to demonstrate working 
# of map.

# Return double of n
def addition(n):
return n + n

# We double all numbers using map()
numbers = (2, 4, 6, 8)
result = map(addition, numbers)
print(list(result))

Output:

[4, 8, 12, 16]
0 Shares:
You May Also Like
Read More

Multithreading in Python

Definition: Multithreading in Python involves running multiple threads within a single process to perform concurrent tasks, allowing for…