DEV Community

Cover image for Python map() Method Explained
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on • Originally published at Medium

4 2

Python map() Method Explained

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.']
Enter fullscreen mode Exit fullscreen mode

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.']
Enter fullscreen mode Exit fullscreen mode

You can learn more about the method here.

Article posted using bloggu.io. Try it for free.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay