Pass multiple arguments to the map() function in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Pass multiple arguments to the map() function in Python #

To pass multiple arguments to the map() function:

  1. Pass the handler function and the arguments to the functools.partial() method.
  2. Pass the result and the iterable to the map() function.
  3. The handler function will get called the arguments on each iteration.
main.py
from functools import partial my_list = [1, 2, 3, 4] def example_func(item, extra_arg): print(item, extra_arg) return item + extra_arg my_arg = 100 new_list = list( map(partial(example_func, extra_arg=my_arg), my_list) ) print(new_list) # 👉️ [101, 102, 103, 104]

We used the functools.partial method to pass multiple arguments to the map() function.

The method takes a function, positional and keyword arguments and returns a partial object.

When the partial object is called, it behaves as if the function was called with the provided arguments.

When using the functools.partial() method, it's best to pass the arguments as keyword arguments to not mix up the order.

An alternative approach is to use a list comprehension.

To map a function with multiple arguments:

  1. Use a list comprehension to iterate over each element of the iterable.
  2. Call the function, passing it each element and the extra arguments.
  3. The list comprehension will call the function for every element.
main.py
def example_func(item, extra_arg): print(item, extra_arg) return item + extra_arg my_list = [1, 2, 3, 4] my_arg = 100 new_list = [example_func(item, my_arg) for item in my_list] print(new_list) # 👉️ [101, 102, 103, 104]

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

Instead of using map(), in most cases you can just use a list comprehension and make your code a bit easier to read.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.