How to Enumerate in Python
To keep track of iterations in Python we can add an index to an iterable using the enumerate()
function.
In this tutorial, we will learn how to make iterable data types such as lists, strings and objects in Python enumerable.
The enumerate() Function Syntax
enumerate()
takes two arguments, firstly the iterable data and secondly the start index. The second argument is optional and the default index will be 0
if a custom one isn't supplied.
enumerate(iterable, [startIndex])
Create an Enumerable Object
In the example below, we will enumerate a list
with indexes starting at 1
before converting the enumerable object back to a list
.
fruit = ['apples', 'oranges', 'apricots', 'strawberries']
fruitEnumerate = list(enumerate(fruit, 1))
print(fruitEnumerate)
[(1, 'apples'), (2, 'oranges'), (3, 'apricots'), (4, 'strawberries')]
As you can see in the output, the list
fruitEnumerate
now contains index/value key pairs that start from 1
.
Loop Over an Enumerable Object
We can use a for loop to iterate over an enumerable object.
fruit = ['apples', 'oranges', 'apricots', 'strawberries']
fruitEnumerate = enumerate(fruit)
for item in fruitEnumerate:
print(item)
(0, 'apples')
(1, 'oranges')
(2, 'apricots')
(3, 'strawberries')
To use the index/value key pairs separately we can pass two iteration variables into the for
loop. The first is the index
and the second is the value
.
fruit = ['apples', 'oranges', 'apricots', 'strawberries']
fruitEnumerate = enumerate(fruit)
for count, value in fruitEnumerate:
print(count, value)
0 apples
1 oranges
2 apricots
3 strawberries
Conclusion
You now know how to enumerate iterables in Python, change the start index value and access the indexes and values inside a for
loop.