Online Tutorials & Training Materials | STechies.com
Register Login
Advertisement

What Does Enumerate() Function Do in Python?

|| 0

What Does Enumerate() Function Do in Python?
Stechies

In python we use enumerate() function to keep the count or track of iterations while using iterators over a tuple or list.

Python enumerate() function create a counter in the iterations and return the iteration count in the form of object.

Parameters

iterable - Objects that supports iteration.
start (optional) - Value from which index will start, By default it is set to ‘0’, we can reset to any value.

Here in this article we have explained how to use enumerate() function with list, loop and string with example.

Enumerate() List

# Python program to Enumerate() with List

list1 = ["Red","Blue","Green","Orange"]

# creating enumerate
obj1 = enumerate(list1)

print("Return type:",type(obj1))
print(list(enumerate(list1)))

Output:

Return type: <class 'enumerate'>
[(0, 'Red'), (1, 'Blue'), (2, 'Green'), (3, 'Orange')]

Enumerate() change start index to 10 

# Python program to Enumerate() with List

list1 = ["Red","Blue","Green","Orange"]

print(list(enumerate(list1, 10)))

Output:

[(10, 'Red'), (11, 'Blue'), (12, 'Green'), (13, 'Orange')]

Python Enumerate for loop

# Python program to Enumerate() with List

list1 = ["Red","Blue","Green","Orange"]

# printing the list in object directly
for index,value in enumerate(list1):
  print("index: ", index, "Value: ",value)

# changing start index to 100
for index,value in enumerate(list1,100):
  print("index: ", index, "Value: ",value)

Output:

index:  0 Value:  Red
index:  1 Value:  Blue
index:  2 Value:  Green
index:  3 Value:  Orange
index:  100 Value:  Red
index:  101 Value:  Blue
index:  102 Value:  Green
index:  103 Value:  Orange

Enumerate String Python

# Python program to Enumerate() with String
string1 = "Stechies"

# printing the string in object directly
for index,value in enumerate(string1):
  print("index: ", index, "Value: ",value)

# changing index to 100
for index,value in enumerate(string1,100):
  print("index: ", index, "Value: ",value)

Output:

index:  0 Value:  S
index:  1 Value:  t
index:  2 Value:  e
index:  3 Value:  c
index:  4 Value:  h
index:  5 Value:  i
index:  6 Value:  e
index:  7 Value:  s
index:  100 Value:  S
index:  101 Value:  t
index:  102 Value:  e
index:  103 Value:  c
index:  104 Value:  h
index:  105 Value:  i
index:  106 Value:  e
index:  107 Value:  s

Python Enumerate Dictionary

We don’t use enumerate() function with Dictionaries & Sets because Dictionaries and Sets are not in sequence.


Advertisement
Advertisement
Advertisement