Python map Function | Data Structure| Multiple arguments | Examples

Python map function or map data structure implements a given function to each item of an iterable (list, tuple, etc.) and returns a list of the results. In this tutorial, you will learn an overview of the python map function with examples.

Python map Function | Data Structure| Multiple arguments | Examples

Syntax of map() function

Here is the simple syntax of it.

map(function, iterable, ...)

Parameter Values

  • function – The function (add, square input, etc) to execute for each item (Required)
  • iterable –  A sequence, collection, or an iterator object. You can send as many iterable as you like, just make sure the function has one parameter for each iterable.

You can pass more than one inerrable to the map() function.

Return Value

Python map returns multiple values, The returned value from the map() object then you can pass to functions to get required values, like sets (to create a set), lists (to create a list).

Python map function example

This is a very simple and easy python map example. In this example, we are passing tuple in the map() function. Where the tuple value goes into function one by one and gets the length. Then after just print the result in a list format.

# get the length function
def myfunc(n):
    return len(n)

result = map(myfunc, ('EyeHunts', 'Python', 'Tutorial'))

# get the list
print(list(result))

Output: [8, 6, 8]

As the upper code example and output, there is a duplicate value. If you don’t want it, you can use a set of data types instead of lists. All duplicate elements will be removed.

# get the length function
def myfunc(n):
    return len(n)


result = map(myfunc, ('EyeHunts', 'Python', 'Tutorial'))

# get the list
print(set(result))

Output: {8, 6}

Let’s do another example with gets the square of numbers.

# square function
def myfunc(n):
    return n * n


result = map(myfunc, (1, 2, 3))

# get the list
print(list(result))

Output: [1, 4, 9]

Q: How do put multiple arguments into a map function of Python?

Answer: In python map() function takes only two arguments, a function, and a sequence (tuple, lists, etc.).

what do you mean by Python map multiple arguments?

You can pass multiple arguments in a function, you can use a python lambda function to get done this task, check this example.

# add numbers function
def func(a, b):
    return a + b


list1 = [4, 2, 3, 4]
list2 = [5, 1, 7, 8]

result = map(lambda x, y: func(x, y), list1, list2)
print(list(result))

Output: [9, 3, 10, 12]

Do comment if you have any doubt and suggestion in this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples Python map function are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.