• Register
100 points
3

Today I am going to talk about how to iterate through the list and print the index and value of each element of the list. There are several ways of completing this task but today we are going to talk about a type of low-level design pattern in python which is called an idiom. This idiom is called ENUMERATE. To understand the significance of this function, I will bring a method that you might be familiar with but is not recommended to use.

Let’s take a list of names: Bob, Mary, Sam, Ann:
 

 a = [‘Bob’, ‘Mary’, ‘Sam’, ‘Ann’]

For the traditional method you would do something like this:

​
index = 0
for value in list:
    print(index, value)
    index += 1 

​

As you can see, first we assign an index as 0 out of for loop and start iterating through a list. For each step, we print the index and value of an element and increase an index by one using += operation. Remember that this method is very inefficient and not recommended for future use.

Now if we look at an example of ENUMERATE function we will see that it is the most efficient way of iterating through a list and getting the value and index of each element:

for value, index in enumerate(list):
    print(value, index)

As you can see, enumerate function gives us the ability to iterate through the list and get the value and index of each element in a very efficient manner. This method is recommended for every programmer and its usage can be something that might make you stand out from other python developers.
 

100 points
3