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

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
2 min

banner

# 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 = ['Bobby', 'Hadz', 'Com'] 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) # ๐Ÿ‘‰๏ธ ['Bobby0', 'Hadz1', 'Com2']

get access to index in map function

The code for this article is available on GitHub

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 is 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.

# Get access to the Index in the map() function using a list comprehension

This is a three-step process:

  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 = ['Bobby', 'Hadz', 'Com'] result = [item + str(idx) for idx, item in enumerate(my_list)] print(result) # ๐Ÿ‘‰๏ธ ['Bobby0', 'Hadz1', 'Com2']

get access to index in map using list comprehension

The code for this article is available on GitHub
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've also written an article on how to pass multiple arguments to the map() function.

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.

Copyright ยฉ 2024 Borislav Hadzhiev