What does enumerate() mean in python ?

Last Updated On Tuesday 22nd Mar 2022

enumerate python

The enumerate() function adds a counter to an iterable.So for each element in cursor, a tuple is produced with (counter, element).

  • By default, enumerate() starts counting at 0.
  • If you give it a second integer argument, it’ll start from that number instead.
	for count, value in enumerate(["a", "b", "c"]):

print(count, value)

# 0 a
# 1 b
# 2 c

python enumerate

	li = ['apple', 'banana', 'grapes', 'pear']
for counter, value in enumerate(li):
    print counter, value

# Output:
# 0 apple
# 1 banana
# 2 grapes
# 3 pear
	li = ['apple', 'banana', 'grapes', 'pear']
print(list(enumerate(li, 1)))

# Output: [(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]
  • You can use enumerate on any iterable, be it lists, sets, dictionaries, strings, objects, etc
  • Enumerate keeps your code clean by performing the same function with fewer lines of code.
  • It’s an automatic counter and can be used to change the starting value of the index as well by specifying the appropriate value in the second parameter.