enumerate() overview
The enumerate() function in Python adds a counter to an iterable and turns it into and enumerate type.
enumerate() lists
To enumerate an list, use the enumerate() function and it adds a count to each element.
# enumerate list
myList = ['hello', 'world', '!']
enumerated = enumerate(myList)
print(list(enumerated))
The list is enumerated, and an enumerated object is returned.
To print the enumerated list, we use the list() function to turn it into an list again.
[(0, 'hello'), (1, 'world'), (2, '!')]
To see the of the return use type().
# enumerate list
myList = ['hello', 'world', '!']
enumerated = enumerate(myList)
print(type(enumerated))
The list has been turned into an enumerate.
<class 'enumerate'>
enumerate() in loops
The enumerate() function is useful to loop over items in an object and provides a counter.
# enumerate() in loop
myList = ['hello', 'world', '!']
for counter, element in enumerate(myList):
print(counter, element)
The counter and the element are printed.
0 hello
1 world
2 !
enumerate start at specific position
Use the second argument of enumerate() to start at a specific position in the element.
# enumerate() in loop - start at position 1
myList = ['hello', 'world', '!']
for counter, element in enumerate(myList, 1):
print(counter, element)
We have specified that enumerate starts the counter at 1, not 0.
1 hello
2 world
3 !
enumerate() syntax
The syntax of enumerate() is:
enumerate(object, start=0)
enumerate() arguments
The enumerate() functions accepts one or two arguments:
required: object, the object to enumerate
optional: start, the position to start the count. Default value: 0.
If the start position is not given, enumerate() starts the count at 0.
enumerate() return value
The enumerate() function adds a counter to the object and returns an enumerated object.
The returned object has to be converted using list() or tuple() before printing or using it.