What is enumerate in Python

The enumerate in Python is a built-in function. It takes an iterable object. And returns an iterator that produces tuples.

The iterable object could be a list, tuple, or string. Moreover, it contains the index and the value of each element of the object.

Here’s an example. Here we can use enumerate to iterate over a list and print the index and value of each element.

Let’s take a look at the code.

fruits = ['apple', 'banana', 'mango']
for i, fruit in enumerate(fruits):
    print(i, fruit)

# output
0 apple
1 banana
2 mango

We will see more functionalities of this enumerate function in Python.

However, for the beginners, it would be good to take a look at how the for loop works.

In Python, we use a for loop to iterate over a sequence. Certainly it could be a list, tuple, or string. Or it’s an iterable object, such as a dictionary. 

Here is the basic syntax for a for loop in Python:

for item in sequence:
    # code to be executed for each item in the sequence

Mark the indentation, because it’s very important.

For example, we can think of a for loop that iterates over a list of integers and prints each one to the console:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

#output:
1
2
3
4
5

We can also use the range() function to specify a range of values to iterate over. 

For example:

for i in range(4):
    print(i, end=' ')

#output
0 1 2 3 

We can also specify a starting and ending value for the range. Consequently, we can add a step value, like this:

for i in range(1, 11, 7):
    print(i)

# output
1
8

Finally, we can use the enumerate() function to iterate over a sequence. And we can get the index of each element in the sequence. 

For example we can think of the following situation.

names = ['John', 'Json', 'Emily', 'Caty']

for i, name in enumerate(names):
    print(i, name)

# output
0 John
1 Json
2 Emily
3 Caty

As we can see, the enumerate in Python returns an iterator of tuples. 

The tuple consists of an index and the corresponding element from the input iterable.

The index starts at 0 by default.

But we can always specify a different starting index by passing it as an argument to the enumerate function.

By the way, we can also use enumerate with a for loop to iterate over a list and perform some operation on each element. 

For example:

fruits = ['apple', 'banana', 'mango']
for i, fruit in enumerate(fruits):
    fruits[i] = fruit.upper()
print(fruits)

# output
['APPLE', 'BANANA', 'MANGO']

For more python primer code please visit our GitHub Repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

TensorFlow, Machine Learning, AI and Data Science

Flutter, Dart and Algorithm

C, C++, Java and Game Development

Twitter

Comments

Leave a Reply