+ 2
what is the use of Enumerate in python ?
I have been learning since a while. I always wondered what enumerate could be useful for ? Need instances where enumerate could be useful
2 odpowiedzi
+ 7
Any time you need an iterator to include an automatically generated key or "id". Useful in some cases when converting a list to a dictionary using its elements as values and enumeration as keys:
a = list(range(50, 20, -3))
b = dict(enumerate(a))
print(b)
>>>
{0: 50, 1: 47, 2: 44, ..., 9: 23}
+ 5
For further information,
In Python enumerate has 'start' argument with a default value as 0
eg:
a=['a','b','c']
enumerate(a) or enumerate(a,start=0) or enumerate(a,0) gives
[(0,'a'),(1,'b'),(2,'c')]
similarly enumerate (a,2) will give
[(2,'a'),(3,'b'),(4,'c')]