Skip to content

Python map Function: Transforming Iterables without Loops

Python map Function Transforming Iterables without Loops Cover Image

In this tutorial, you’ll learn how to use the built-in Python map() function. This function allows you to process and transform, or “map”, items in an iterable without needing to use a loop to iterate. The function allows you to write incredibly readable code, which specifies the intention of what you’re doing.

By the end of this tutorial, you’ll have learned:

  • What the Python map() function is
  • How the Python map() function is a good alternative to for loops and list comprehensions
  • How to use the Python map() function with built-in functions, custom functions, and lambda functions
  • How to use the Python map() with lists, tuples, and dictionaries
  • Using string methods with the Python map() function to manipulate strings
  • How to transform multiple inputs with the Python map() function

Understanding the Python map() Function

The Python map() function allows you to transform all items in an iterable object, such as a Python list, without explicitly needing to loop over each item. The function takes two inputs: a function to use to map each item and an iterable to transform.

Let’s take a look at the function and its parameters:

# Understanding the Python map() function
map(
    func,       # The function to be applied
    iterable    # The object to be iterated over
)

As you can see, the function takes another function as its input. In this case, you’d use the function object – meaning that you omit using the parentheses.

The best way to understand the function is by looking at an example. Let’s take a list of strings and transform it to a list of the strings’ lengths, by using the len() function:

# Using the map() Function to Count Letters
words = ['hello', 'and', 'welcome', 'to', 'datagy']

lengths = map(len, words)
lengths_list = list(lengths)
print(lengths_list)

# Returns: [5, 3, 7, 2, 6]

Let’s break down what we did in the code above:

  1. We defined a list, words, which holds a number of different strings
  2. We then used the map() function, passing in the len function object and the list we created before
  3. Because this returns a map object, we need to convert it back to a list using the list() function
  4. Finally, we printed the list containing out lengths

So, let’s see what is actually happening: the map function takes the transformation function (in this case, the len function object) and the iterable that we want to transform. The map function implicitly loops over each item and applies the function to each item.

It’s important to know that the map function is written in C, meaning that it’s highly optimized. Because of this, it can actually be more efficient than a regular, explicit for loop. In the next section, you’ll learn how this compares to using for loops or list comprehensions.

Python map() as an Alternative to For Loops and Comprehensions

In this section, you’ll learn how to take on the same transformation as we did above but using Python for loops and list comprehensions. Let’s first take a look at how to use a for loop to do this:

# Using a Python For Loop to Transform List Values
words = ['hello', 'and', 'welcome', 'to', 'datagy']

lengths_list = []
for word in words:
    lengths_list.append(len(word))

print(lengths_list)
# Returns: [5, 3, 7, 2, 6]

Let’s break down what we did here:

  1. We instantiated an empty list to hold our transformed values
  2. We then looped over each word in our list
  3. We then appended the length of each word to our container list

Using a for loop requires us to first create an empty list. Because of this, the code is longer and (perhaps) less readable. Let’s see how we can do this exact same thing with a list comprehension:

# Using a Python List Comprehension to Transform List Values
words = ['hello', 'and', 'welcome', 'to', 'datagy']
lengths_list = [len(word) for word in words]

print(lengths_list)
# Returns: [5, 3, 7, 2, 6]

We can see that this code is much shorter! Not only did we not need to instantiate an empty list, but we were also able to streamline the code quite a bit.

So, when would you use the map() function? The map function is faster than for loops and it also expresses the intention of the code much better. It’s immediately clear that you’re taking one iterable and mapping a transformation function to it.

Because striving for readability in your code is important, this can be an important thing to consider when choosing which approach to use!

How to Use Python map() With Custom Functions

One great thing about the Python map() function is that you can pass in any kind of Python callable into it. This means that you can pass in a built-in function, a custom function, classes, and more. Really, the main requirement is that the function can accept and return a value.

Let’s see how we can develop a custom function and use it with the Python map() function! We can build a function that takes a value and maps it to the cube of that value:

# Using Python map() With a Custom Function
def cube(num):
    return num ** 3

numbers = [1, 2, 3, 4, 5]
cubes = list(map(cube, numbers))

print(cubes)

# Returns: [1, 8, 27, 64, 125]

Let’s break down what we did here:

  1. We defined a function, cube that takes a number as its input. The function returns the number raised to the power of three.
  2. We then created a list, numbers, that holds the values from one through five
  3. The list, cubes, is a list that is created by passing in our new function and the list of values into the map() function

By using custom functions, you’re able to enhance the usefulness of the map() function quite a bit! In the next section, you’ll learn how to use anonymous lambda functions in the Python map() function.

How to Use Python map() With Lambda Functions

Something you’ll encounter very frequently is the use of anonymous lambda functions in the Python map() function. In some cases, you’ll only want to perform the transformation a single time. In these cases, it can be helpful to use a lambda function, which isn’t defined outside of the scope of the map() function.

Let’s see how we can use a lambda function inside of the map() function by replicating our earlier example of cubing values:

# Using Python map() With a Lambda Function
numbers = [1, 2, 3, 4, 5]
cubes = list(map(lambda x: x**3, numbers))

print(cubes)

# Returns: [1, 8, 27, 64, 125]

We can see how much simpler this code is! Because the transformation function is defined inside the map() function, we’re able to immediately understand what the function is intended to do.

How to Use Multiple Inputs with Python map()

One of the great things about the Python map() function is that it can process multiple iterables at once. This is done by passing in multiple arguments following the transformation function argument.

Let’s see how we can use two lists containing numbers and multiply the values together:

# Using Multiple Iterables with Python map()
numbers = [1, 2, 3, 4, 5]
more_numbers = [10, 20, 30, 40, 50]

mapped = list(map(lambda x, y: x*y, numbers, more_numbers))

print(mapped)

# Returns: [10, 40, 90, 160, 250]

This can be a little confusing at first glance, so let’s break down exactly what we did here:

  1. We defined two lists, numbers and more_numbers
  2. We then created a list, mapped, that is the result of passing in a lambda function that takes two parameters and multiplies them together. The lists are passed in sequentially.
  3. The map() function then iterates over each index of the two lists sequentially.

Using String Methods in Python map()

You can also apply Python string methods to items in a list using the Python map() function. This allows you to apply string style transformations to each item in a Python list. Because the map() function accepts not just functions but also methods, we can pass in a string method callable.

Let’s see how we can turn a list of lower case strings into all capital letters:

# Using String Methods with Python map()
quiet = ['hello', 'world', 'how', 'are', 'you']
yell = list(map(str.upper, quiet))

print(yell)

# Returns: ['HELLO', 'WORLD', 'HOW', 'ARE', 'YOU']

In this case, our string method didn’t have a parameter. There may be times, however, when you need to pass in a parameter. For example, when you want to use the replace() method, you need to pass in arguments. For this, we can use a lambda function:

# Using String Methods with Arguments in Python map()
words = ['hello!', '!world', 'ho!w', 'ar!e', 'you!']
cleaned = list(map(lambda x: x.replace('!', ''), words))

print(cleaned)

# Returns: ['hello', 'world', 'how', 'are', 'you']

Using Python map() with Dictionaries

So far, we’ve only looked at working with lists in the Python map() function. However, you can also work with other iterables such as dictionaries. This works in the same way, though you need to decide whether or not to access keys or values in the dictionaries.

Let’s take a look at an example. Say we have a list of dictionaries that contain lengths and widths for different rectangles and we want to create a new key that contains their area. In order to do this, we could write the following:

# Working with Dictionaries in the Python map() Function
measurements = [
    {'length': 1.2, 'width': 2.1},
    {'length': 3.2, 'width': 3.5},
    {'length': 1.2, 'width': 1.5},
]

areas = list(map(lambda x: x['length'] * x['width'], measurements))
print(areas)

# Returns: [2.52, 11.200000000000001, 1.7999999999999998]

Using Python map() with Tuples

Similarly, we can apply the Python map() function on tuples. Because this looks very similar to applying it to Python lists, let’s take a look at a more interesting example. Imagine we have a tuple that contains some values. We want to return a tuple of tuples that contains the original value and the value squared.

Let’s see how we can do this:

# Using Python map() with Tuples
values = (1,2,3,4,5)
squares = tuple(map(lambda x: (x, x**2), values))

print(squares)

# Returns:
# (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)

Let’s break down what we did here:

  1. We defined a tuple containing values from 1 through 5
  2. We then created a new tuple that is created by mapping a lambda function. The lambda function creates a tuple that contains the original value and the value squared.

Conclusion

In this tutorial, you learned how to use the Python map() function. You first learned how the function works, both in theory and by applying it to a list. You then learned how the function compares to using Python for loops and list comprehensions.

Then, you learned how to use the Python map() with custom functions as well as anonymous lambda functions. Then, you learned how to use the map() function with dictionaries and tuples.

Additional Resources

To learn more about related topics, check out the tutorials below:

Leave a Reply

Your email address will not be published.