Last updated: Apr 8, 2024
Reading timeยท2 min
To get access to the index in the map function:
enumerate()
function to get an object of index/item tuples.map()
.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']
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.
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.
def example_func(idx_and_item): index, item = idx_and_item return item + str(index)
An alternative is to use a
list comprehension with
the enumerate()
function.
This is a three-step process:
enumerate()
function to get an object of index/item tuples.my_list = ['Bobby', 'Hadz', 'Com'] result = [item + str(idx) for idx, item in enumerate(my_list)] print(result) # ๐๏ธ ['Bobby0', 'Hadz1', 'Com2']
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.