What is Enumerate in Python

The enumerate() function in Python adds a counter to the iterable and returns an enumerate object. While dealing with iterables, there may arise some situations where we need to add a counter as a key to the iterable. In such cases, the enumerate() method comes useful. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method
Syntax: enumerate(iterable, start=0)
- Iterable – any object that supports iteration
- Start: the index value from which the counter is to be started, by default it is 0.
Let us see an example and understand this method.
li = ["red", "blue", "green"] ob1 = enumerate(li) print(type(ob1)) print(ob1) print(list(ob1)) print() st = "Python" ob2 = enumerate(st) print(type(ob2)) print(ob2) print(list(ob2))
Output:
<class 'enumerate'> <enumerate object at 0x0000024A02670440> [(0, 'red'), (1, 'blue'), (2, 'green')] <class 'enumerate'> <enumerate object at 0x0000024A02670500> [(0, 'P'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')]
Subscribe
Login
Please login to comment
0 Discussion