Map function in python

Learn how to use the map() function in Python programming. Like how to use it? And how it is enforced using proper rules.

This map() method is performing specific function which are operated by each item of the given iterable object. Let as see its syntax.

map(fun, iterables)

The first parameter of this method can be a function object or a lambda expression. The other parameters of this method represent the iterable objects whose items are passed to the function object. Note that this method accepts at least 2 parameters.

Here iterables object can be (such as list, dict, tuple etc). And this method are return a map instance.

This method is often used when each item of an iterable object needs to be represented by a specific method.

Map function example 1

# map() method example 1
def is_even(x):
    if(x % 2 == 0) :
        return True
    return False

# Given list
num = [3,1,2,0,-3,8,7]

# Get status of even number 
obj = map(is_even,num)

# obj to list
result = list(obj)

# Print values
print(obj)
print(result)
Python map function example 1
<map object at 0x7f5b623cd4a8>
[False, False, True, True, False, True, False]

This method are return an instance object before use its result we need to typecast.

Map function example 2

def myIteam(x, y):
  return x + '-' + y

obj = map(myIteam,('one', 'two', 'tree', 'four'),
                  ("logic","game","year","winner"))
result = tuple(obj)
# print tuple value
print(result)
Python map function example 2
('one-logic', 'two-game', 'tree-year', 'four-winner')

Map function example 3

We can replace custom function using lambda expression.

# Example 3 map() with lambda function
obj = map(lambda a, b : a + '-' + b,('one', 'two', 'tree', 'four'),
                  ("logic","game","year","winner"))
result = tuple(obj)
# print tuple value
print(result)
('one-logic', 'two-game', 'tree-year', 'four-winner')



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved