Python map()

📔 : Python 🔗

map() function Iterable Objects(list, tuple, set) के प्रत्येक element को user defined callback function में send करता है , और एक new values के साथ return करता है।


Basically map() function का use Iterable Objects(list, tuple, set) के हर एक element को callback function के through visit करने के लिए किया जाता है। element को as a parameter automatically pass कर दिया जाता है।

What is Callback Function ?

Callback Functions वो function होते हैं जो किसी दूसरे function में as an arguments pass किये जाते हैं। और जिस function में ये pass किये जाते हैं उन्हें Higher - Order Function कहते हैं।

Python map() Syntax

map(callback, iterables)
  1. callback | required : यह user define function है , function normal भी हो सकता है या आप चाहे तो lambda Function भी use कर सकते हैं।

  2. iterables | required : यह Iterable object है जिसके हर एक element को विजिट करना है। आप के according कितने ही iterables pass कर सकते हैं , लेकिन कम से कम एक तो pass होना ही चाहिए।

Python map() Example

Copy Fullscreen Close Fullscreen Run
# define a function.
def calculate(num) :
  return num+10;

# visit every element of a list.
l = [12,23,45,34,5]
print("Before Iteration")
print(l)
res = map(calculate, [12,23,45,34,5])
print("After Iteration")
# map function return obejct so we have to type cast it another format.
print(list(res)) 
Output
C:\Users\Rahulkumar\Desktop\python>python pythonMap.py
Before Iteration
[12, 23, 45, 34, 5]
After Iteration
[22, 33, 55, 44, 15]

example में map() function को एक list के ऊपर apply किया गया है ,हालाँकि आप अपनी need के according दूसरे Iterable Objects(list, tuple, set) पर भी apply कर सकते हैं।

map() with lambda function

अब एक और example देखते हैं जिसमे एक से ज्यादा iterable Objects को lambda function के साथ pass करते हैं।

Copy Fullscreen Close Fullscreen Run
# now use two tuple objects with lamda function.
res = map(lambda num1, num2 : num1*num2, (2,3,4,5,6,7,8), (2,3,4,5,6,7,8)
print(list(res)) 
Output
C:\Users\Rahulkumar\Desktop\python>python pythonMap.py
[4, 9, 16, 25, 36, 49, 64]

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook