Python enumerate() will receive a sequence to return an enumerate object. In this tutorial, we will use some examples to help you understand it.
Python enumerate()
It is defined as:
enumerate(iterable, start=0)
Here iterable will be a sequence.
For example:
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] s = enumerate(seasons) print(s)
Here s is <enumerate object at 0x00000210075D27E0>.
How about value in enumerate object?
An enumerate object will contains some values that are (index, value).
For example:
for i, ele in s: print(i, ele)
Run this code, we will get:
0 Spring 1 Summer 2 Fall 3 Winter
Here we see the index starts with 0, we also can change it.
For example:
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] s = enumerate(seasons, 4) for i, ele in s: print(i, ele)
Then, we can see:
4 Spring 5 Summer 6 Fall 7 Winter
Here the index starts with 4.
Python enumerate.__next__()
We can use enumerate.__next__() to get value in an enumerate one by one.
For example:
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] s = enumerate(seasons, 4) t = s.__next__() print(t) t = s.__next__() print(t)
Run this code, we will see:
(4, 'Spring') (5, 'Summer')