This article will explain the map() function in Python and show you how to use it.
The Python map() function applies a given function for all items in an iterable (iterables are things like lists, dictionaries, sets, or tuples – collections containing items that can be looped over).
The syntax and code in this article will work for both Python 2 and Python 3.
Syntax for Python map()
The map() function is built into Python, so nothing needs to be imported. Here’s the syntax:
- FUNCTION is a standard Python function, previously defined in your code
- It should accept a single parameter which is used to read each item in the iterable passed to the map() function
- The return value of this function will be added to the return values from the map() function
- ITERABLE should be a variable or value containing an iterable
- Lists, dictionaries, sets, and tuples are common iterables. Strings are also iterable – you can pass a string to map(), and the FUNCTION will be run on each character in the string
- map() will return an iterator (an object containing several values) containing each return value from the given FUNCTION
Example usage of map()
This example uses map() to modify each item in a list – in this case, a list of animals. Then, it will add some extra text to each item and store the result in a new list.
# Define a list of animals animals = ['sharks', 'bears', 'birds'] # Define the function we wish to run for each item in the above list # This function takes a single parameter - the current item being processed from the list, and returns that item with some added text def coolFunction(item): return item + ' are cool' # Use the map() function to run coolFunction on every item in the animals list # It is being stored in a new variable, animalsAreCool, but you could overwrite the original animals variable if you wanted to animalsAreCool = map(coolFunction, animals) # Loop over the result and print out each item for item in animalsAreCool: print(item)
The above example will output:
sharks are cool bears are cool birds are cool
As it has created a new iterator containing the updated text.
Similar Python Functions
Several other Python Functions work similarly to map() but may suit your scenario better – give them a look:
- filter() – better for removing items from a list
- map() – better for performing operations on each item in a list
- functools.reduce() – better for aggregating data from a list (e.g., collecting data from each item and summing it)
- itertools.accumulate() – better for aggregating data from a list while storing the result of each step in the aggregation process