Python map() Function

Python map() Function

The Python 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.)

The Python map() Function is used to return a list of results after applying a given function to each item of an iterable(list, tuple etc.)

 

For every element present in the given sequence, apply some functionality and generate new element with the required modification. For this requirement we should go for map() function.

Eg: For every element present in the list perform double and generate new list of doubles.

Syntax: map(function, sequence)

function– It is a function in which a map passes each item of the iterable.

iterables– It is a sequence, collection or an iterator object which is to be mapped.

Return -It returns a list of results after applying a given function to each item of an iterable(list, tuple etc.)

# List of strings

l = [‘sat’, ‘bat’, ‘cat’, ‘mat’]

 

# map() can listify the list of strings individually

test = list(map(list, l))

print(test)

OUTPUT:

[[‘s’, ‘a’, ‘t’], [‘b’, ‘a’, ‘t’], [‘c’, ‘a’, ‘t’], [‘m’, ‘a’, ‘t’]]

 

The function can be applied on each element of sequence and generates new sequence.

Without Lambda

1) l=[1,2,3,4,5]

2) def doubleIt(x):

3) return 2*x

4) l1=list(map(doubleIt,l))

5) print(l1) #[2, 4, 6, 8, 10]

 

With Lambda

1) l=[1,2,3,4,5]

2) l1=list(map(lambda x:2*x,l))

3) print(l1) #[2, 4, 6, 8, 10]

Related Posts:

Python Tutorial – Learn Python

What is Python? What makes Python so Powerful?

Variables in Python – Constant, Global & Static Variables

Namespacing and Scopes in Python

Operators in Python

Data Types in Python

STRING Data Type in Python

LIST Data Structure in PYTHON

TUPLE Data Structure in PYTHON

Differences between List and Tuple

SET Data Structure in PYTHON

DICTIONARY Data Structure in PYTHON

Database Programming in Python

What is Multithreading in Python?

Python Exception Handling Using try, except and finally statement

File Handling in Python

Python Random module

Python reduce() Function

Python filter() Function

Lambda Function in PYTHON (Anonymous Function)

Python Interview Question And Answers