Using the Python ‘map()’ Function to Process a List, With Examples

Using Python Map()

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:

map(FUNCTION, ITERABLE) 

Note that:

  • 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:

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *