Python map() Method Explained
I am a software engineer with 4 years of professional experience, currently specializing in full-stack development.
I work a lot with HTML, CSS, JavaScript, and Python and regularly use React, Vue, and Django to build single-page applications and marketing landing pages.
I also work with React Native to build mobile applications with optimized experiences and for businesses who want to ship products in the market quickly.
Currently, I am a part of a team of 8 as a full-stack engineer where I focus on accessibility, component-driven approaches, and building systems that can scale with ease.
Do you know that it's possible to process iterables without a Loop? The map method is really useful when you need to perform the same operation on all items of an iterable (list, sets, etc).
The map() method takes two arguments:
- a function object
- an iterable or multiple iterable
The function passed to the map() method will perform some action on each element of the iterable passed as an argument.
Example
>>> fruits = ["lemon", "orange", "banana"]
>>> def add_is_a_fruit(fruit):
... return fruit + " is a fruit."
...
>>> new_fruits = map(add_is_a_fruit, fruits)
<map object at 0x7f7fe85e6460>
>>> new_fruits = list(new_fruits)
>>> new_fruits
['lemon is a fruit.', 'orange is a fruit.', 'banana is a fruit.']
Notice that you have to convert the returned map object into an iterable so you can work with it easily.
It's also possible to use map() with lambda functions.
>>> new_fruits = map(lambda fruit: fruit + " is a fruit.", fruits)
>>> new_fruits = list(new_fruits)
>>> new_fruits
['lemon is a fruit.', 'orange is a fruit.', 'banana is a fruit.']
You can learn more about the method here.
Article posted using bloggu.io. Try it for free.




