Get access to the Index in the map() function in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Get access to the Index in the map() function in Python #

To get access to the index in the map function:

  1. Use the enumerate() function to get an object of index/item tuples.
  2. Unpack the index and item values in the function you pass to map().
  3. The function will get passed a tuple containing the index and item on each iteration.
main.py
my_list = ['Alice', 'Bob', 'Carl'] def example_func(idx_and_item): index, item = idx_and_item return item + str(index) result = list(map(example_func, enumerate(my_list))) print(result) # 👉️ ['Alice0', 'Bob1', 'Carl2']

We used the enumerate function to get access to the index in the map() function.

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second - the item.

main.py
my_list = ['apple', 'banana', 'melon'] for index, item in enumerate(my_list): print(index, item) # 👉️ 0 apple, 1 banana, 2 melon

Notice that we had to unpack the elements of the tuple.

main.py
def example_func(idx_and_item): index, item = idx_and_item return item + str(index)
This might not suit your use case (especially if using a one-liner lambda function).

An alternative is to use a list comprehension with the enumerate() function.

To get access to the index in the map function:

  1. Use a list comprehension to iterate over the iterable.
  2. Use the enumerate() function to get an object of index/item tuples.
  3. You can access the index as the first item on each iteration.
main.py
my_list = ['Alice', 'Bob', 'Carl'] result = [item + str(idx) for idx, item in enumerate(my_list)] print(result) # 👉️ ['Alice0', 'Bob1', 'Carl2']
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.