DEV Community

DerekStegall
DerekStegall

Posted on

Introducing Python's map Function

Mapping Function

Hey there! Let’s talk about code and how repetitive it can get. Writing repeated code never looks good to developers. However, sometimes it's hard to avoid. Knowing this, there are tools made to help us shorten code. The tool I'm discussing is the map function. The map function allows you to iterate through a list applying the desired function to each item of the list. Let's break down exactly how this works.

The code snippet below represents a function that takes a number and adds one to it. Given a list of numbers, how can I apply the add_number function to each element in the iterable?

def add_number(number):
    return number + 1

Using the map function, you will pass in the desired function and list as arguments. The given function will then be used over each list item.

def add_number(number):
    return number + 1

numbers = [1, 2, 3]

mapped_numbers = map(add_number, numbers)

print("After Adding 1")
for number in mapped_numbers:
    print(number)

names = ["Guido", "John", "Derek"]

print("Lengths of names")
for name_length in map(len, names):
    print(name_length)

Output:

After Adding 1
2
3
4
Lengths of names
5
4
5

The map function can make long steps, really short. The goal here is to reduce repetitive code. With map, it can be achieved. Now our code can be clean, concise and presentable!

Example

Here's the longer way to reach the goal of this program:


# The function below removes all vowels from the word provided in the argument
def no_vowel(word):
    for ch in "AEIOU":
        word = word.replace(ch, "")
        word = word.replace(ch.lower(), "")
    return word


# We want to remove each vowel from each word in the list below
word_list = ["Captain", "Crunch", "Cereal", "Yummy"]

# With each removed vowel we want to append the new word into the list below
removed_vowel_list = []

for word in word_list:
    removed_vowels = no_vowel(word)
    removed_vowel_list.append(removed_vowels)

string = f"{word_list} --> {removed_vowel_list}"

print(string)

Output

    ['Captain', 'Crunch', 'Cereal', 'Yummy'] --> ['Cptn', 'Crnch', 'Crl', 'Ymmy']

But when using the map() function, here's how the code can be shortened:

    def no_vowel(word):
        for ch in "AEIOU":
            word = word.replace(ch, "")
            word = word.replace(ch.lower(), "")
        return word

    word_list = ["Captain", "Crunch", "Cereal", "Yummy"]

    new_list = list(map(no_vowel, word_list))

    string = f'{word_list} --> {new_list}'

    print(string)

Output

    ['Captain', 'Crunch', 'Cereal', 'Yummy'] --> ['Cptn', 'Crnch', 'Crl', 'Ymmy']

Extra Information on Map

When using map, it's good to know that it is a type of generator. The return value for map is a map object(iterator). Think of it as a list but it can't store data. Map is a lazy generator, meaning it's single use and only evaluates when necessary. Calling a function on map can allow it to be used.

nums = [10, 5, 13, 7]

mapped = map(print, nums) # nothing gets printed

list(mapped) # things get printed (caling function on map)

list(mapped) # nothing gets printed (single use)

For more information on map you can follow the documentation. https://docs.python.org/3/library/functions.html#map

Top comments (0)