The enumerate()
function allows you to iterate through a sequence of objects while keeping track of the index of each item.The function takes one required arguments, an iterable and an optional argument, the start. The iterable is the object containing the elements to enumerate while the start indicates the starting index , it defaults to 0
.
enumerate(iterable, start = 0)
copy
iterable |
Required argument representing the iterable to enumerate. |
start |
An optional integer specifying the starting index. It defaults to 0. |
The function returns an iterable enumerate object containing index-value pairs, where the value is an element from the iterable argument and the index is its index as specified by the start argument.
We can turn the enumerate object to other iterable types such as lists, tuples and set using the relevant constructors, in this case, the resulting object will contain a tuple containing the index-value objects.
When the enumerate object is used with the dict
function, it will result to a dictionary containing the indices as the keys and the values as the dictionary values.
A common use case of the enumerate()
function is with for loops to keep the track of the index of the current iteration element.
Note that using the enumerate()
as in above is more convenient than the alternative approaches. For example, without using enumerate() we would need to use other means to track the current index as shown below.
enumerate() with start
The start
parameter allows us to specify an integer as the starting value for the enumeration. By default, this value is 0.
The start
value can also be negative as shown below.