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
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
Top comments (2)
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
strarguments and actual
mapreturns a generator, so it can be iterated only once. I often solve this with storing the result in a tuple:
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 😀