Search
  • livewithcs

Python enumerate() function

Updated: Oct 4, 2019

Enumerate is built in function of Python. Basically, enumerate() allows you to loop over a collection of items while keeping track of the current item’s index in a counter variable.


Let’s take a look at an example:

name_list = ['Sam', 'Bob', 'Joy']
for index, value in enumerate(name_list):
    print(f'{index}: {value}')                                                 
OUTPUT:
0: SAM
1: Bob
2: Joy

As you can see, enumerate() iterated over the name_list and generated an index for each element by increasing a counter variable starting at zero.


You can also create tuples containing the index and list item using a list . Here is an example

name_list = ['Sam', 'Bob', 'Joy']
list_tuple = enumerate(name_list):
print(list_tuple)   
OUTPUT:
[(0,'Sam'),(1,'Bob'),(2,'Joy')]
131 views

Recent Posts

See All

Python filter() function

1. The filter() alternative a for loop but it is a builtin function and faster. 2. The filter() creates a list of elements for which a function returns true . Let’s take a look at an example: number_l

Bangalore,Karnataka