DEV Community

Max
Max

Posted on • Updated on

Python comparison between normal for loop and enumerate

In Python, we can use the for loop to iterate over a sequence of values, such as a list or a tuple. We can also use the enumerate function to add a counter to the loop. Here's an example to compare the normal for loop with the enumerate function:

Normal For Loop

fruits = ['apple', 'banana', 'orange']
for i in range(len(fruits)):
    print(i, fruits[i])
Enter fullscreen mode Exit fullscreen mode

Output:

0 apple
1 banana
2 orange
Enter fullscreen mode Exit fullscreen mode

In this example, we use the range function to generate a sequence of numbers from 0 to the length of the fruits list. We then use this sequence of numbers to access the elements of the fruits list using their indices.

Enumerate

fruits = ['apple', 'banana', 'orange']
for i, fruit in enumerate(fruits):
    print(i, fruit)
Enter fullscreen mode Exit fullscreen mode

Output:

0 apple
1 banana
2 orange
Enter fullscreen mode Exit fullscreen mode

In this example, we use the enumerate function to add a counter to the loop. The enumerate function returns a sequence of pairs, where the first element of each pair is the index, and the second element is the corresponding value from the fruits list. We unpack each pair into two variables i and fruit, and then print them.

As you can see, using the python enumerate function makes the code shorter and more readable. It also eliminates the need to use the range and len functions to access the elements of the list.

Here's a summary of the differences between the normal for loop and the enumerate function:

  • A normal for loop can iterate over a sequence of values, but does not provide a counter.
  • The enumerate function can iterate over a sequence of values and provide a counter.
  • The enumerate function returns a sequence of pairs, where the first element of each pair is the counter, and the second element is the value from the sequence.
  • Using enumerate can make the code shorter and more readable, and eliminates the need to use the range and len functions to access the elements of the list.

Explore Other Related Articles

Python if-else Statements Tutorial
Python set tutorial
Python tuple tutorial
Python Lists tutorial
Python dictionaries comprehension tutorial

Top comments (0)