Register Login

Understanding the map() function in Python

Updated Jan 08, 2020

In python we use map() function to apply a given function (custom or inbuilt) on all the elements of specified iterable (list, tuple etc.)

When we have to run all the elements of iterable like list, tuple to function one by one and store the output in variable for further use, in this case we use map() function.

Syntax :

map(function, iterables)

function: function to execute (required)

iterables: iterables like, list, tuple (required)

You can Pass multiple iterables to the function

Example:

# Program to explain working on map function
  
# Declare function to join string 
def addname(a, b): 
    return a + ' ' + b 
  
# Create tuples 
fname = ('Green', 'Yellow', 'Orange', 'Blue')
fcolor = ('Apple', 'Mango', 'Orange', 'Berry')

# Pass tuples to addname function
result = map(addname, fname, fcolor)

# Print output
print(list(result))

Output:

['Green Apple', 'Yellow Mango', 'Orange Orange', 'Blue Berry']

map() with built-in function

Example:

# Program to explain working on map function
  
# Create function to convert string to uppercase
def makeupper(a): 
    return a.upper() 
  
# Inilised tuple 
fname = ('Green', 'Yellow', 'Orange', 'Blue')

# Pass tulip to function 'makeupper'
output = map(makeupper, fname)

# Print output
print(list(output))

Output:

['GREEN', 'YELLOW', 'ORANGE', 'BLUE']

map() with lambda keyword

Lambda is a keyword which use to define a function without a name. this can be used with filter(), map() and reduce() functions.

Lambda keyword is also used when we need to define a small function which we don’t want to reuse it.

In the following example we are using lambda keyword to generate same out as mentioned in above example without declaring a function. 

Example:

# Program to explain working on map function with lambda keyword 
  
# Create tuples 
fname = ('Green', 'Yellow', 'Orange', 'Blue')
fcolor = ('Apple', 'Mango', 'Orange', 'Berry')

# Pass tuples ‘fname’ and ‘fcolor’ with lambda keyword
result = map(lambda a, b : a + ' ' + b, fname, fcolor)

# Print output
print(list(result))

Output:

['Green Apple', 'Yellow Mango', 'Orange Orange', 'Blue Berry']

 


×