Python – Map vs List comprehension

Suppose we have a function and we want to compute this function for different values in a single line of code . This is where map() function plays its role ! 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(funcname, iterables)

Parameters:

funcname: It is the name of the function which is already defined and is to be executed for each item.
iterables: It can be list, tuples or any other iterable object.

Return Type: Returns a map object after applying the given function to each item of a given iterable (list, tuple etc.)



Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# function to double the number
def num (n) :
    return n * 2
          
lst = [2, 44, 5.5, 6, -7]
  
# suppose we want to call function
# 'num' for each element of lst,
# we use map
  
# creates a map object
x = map(num, lst) 
print(x) 
  
# returns list
print(list(x))  

chevron_right


Output:

<map object at 0x7f859f3f05c0>
[4, 88, 11.0, 12, -14]

Note: For more information, refer to Python map() function.

List Comprehension is a substitute for the lambda function, map(), filter() and reduce(). It follows the form of the mathematical set-builder notation. It provide a concise way to create lists.

Syntax:

[ expression for item in list if conditional ]

Parameters:

  • Expression – based on the variable used for each element
  • for ..in – ‘for’ followed by the variable name to use, followed by ‘in’
  • if – to filter

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

lst = [2, 44, 5.5, 6, -7]
  
# to double the number
# list comprehension
x = [i * 2 for i in lst ] 
print(x)

chevron_right


Output:



[4, 88, 11.0, 12, -14]

Note: For more information, refer to Python List Comprehension and Slicing.

Map VS List Comprehension