Subscribe

Python map() function

โœ๏ธ

How to use the map() function in Python

5 Jun, 2021 ยท 2 min read

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)

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]

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]

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Speedtest your connection in Python

21 Jun, 2021 ยท 3 min read

Speedtest your connection in Python

F-strings in Python

7 Jun, 2021 ยท 2 min read

F-strings in Python

Join 1513 devs and subscribe to my newsletter