Python enumerate

Python enumerate() builtin function is used to create an enumerate object from a given iterable. The iterable must be a sequence, an iterator, or an object that supports iteration.

In this tutorial, we will learn about the syntax of Python enumerate() function, and learn how to use this function with the help of examples.

Syntax

The syntax of enumerate() function is

enumerate(iterable, start=0)

Each __next__() call on this enumerate object returns a tuple: (index, value from iterable).

where

Parameter Required/Optional Description
iterable Required A sequence, an iterator, or an object that supports iteration.
start Optional An integer. This value represents the starting value of index to be returned in the tuples.

Returns

The function returns enumerate object.

Examples

1 Enumerate Object from a List

In this example, we take a list and create an enumerate object from this list. We use for loop to iterate over this enumerate object.

Python Program

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

Output

(0, 'apple')
(1, 'banana')
(2, 'mango')

2 Enumerate Object with Start Parameter

In this example, we provide start=2 for enumerate function.

Python Program

fruits = ['apple', 'banana', 'mango']
result = enumerate(fruits, start=2)
for x in result:
    print(x)

Output

(2, 'apple')
(3, 'banana')
(4, 'mango')

Conclusion

In this Python Tutorial, we have learnt the syntax of Python enumerate() builtin function, and also learned how to use this function, with the help of Python example programs.