DEV Community

Cover image for Python map() function
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Python map() function

After looking into the Python filter function, let's take a look at how the map works.

As we learned, the filter will return a section of the input based on certain criteria.

Map() function in Python

Let's first have a look at the syntax:

result = map(myFunction, input)
Enter fullscreen mode Exit fullscreen mode

To give more details to this:

  • result: Is the output. This will be a changed sequence.
  • filter: Is the Python built-in function
  • myFunction: This will be a custom function we are going to build
  • input: This is the original sequence we want to map

As you can see, the syntax looks like the filter function. The main change will be inside the myFunction.

Let's say we have a list of numbers that we need to multiply by themselves.

input = [2, 5, 10]

def myFunction(n):
    return n * n

result = map(myFunction, input)
print(list(result))

# [4, 25, 100]
Enter fullscreen mode Exit fullscreen mode

Pretty cool right, and like the filter one, we can use Lambda functions to make it even shorter.

input = [2, 5, 10]

result = map(lambda n: n * n, input)
print(list(result))

# [4, 25, 100]
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (2)

Collapse
 
xtofl profile image
xtofl

Nice! Higher order functions make for very expressive code with less clutter.

Did you know that a constructor can be used as well? For conversion between plain str arguments and actualPath for example:


paths = map(Path, sys.args)
assert all(map(Path.exist, paths))
Enter fullscreen mode Exit fullscreen mode

Caveat, though: map returns a generator, so it can be iterated only once. I often solve this with storing the result in a tuple:


paths = tuple(map(Path, sys.args))
assert all(map(Path.exist, paths))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dailydevtips1 profile image
Chris Bongers

Hi @xtofl ,

I didn't know this yet!
Thanks for the examples, written it down to look at I'm sure this can solve certain issues perfectly 😀