11.3. Enumerate#
Adds number to the list
Counter
Used when you need counter or positions or Indexes
11.3.1. Syntax#
enumerate(list)
Takes list
Returns tupple by default (iterable so has to be converted explicitly)
list1=['a','b']
enumerate(list1) # returns iterable obj <> which is tuple by default but can be converted to list as well
<enumerate at 0x7f8ec20ce540>
print([i for i in enumerate(list1)]) # by default returns tupple we just returned i
print([(i,j) for i,j in enumerate(list1)]) # this is same thing as above
#print([i,j for i,j in enumerate(list1)]) # this will give error because you are explicitly returning two vars
print([[i,j] for i,j in enumerate(list1)]) # can be converted to list as well
[(0, 'a'), (1, 'b')]
[(0, 'a'), (1, 'b')]
[[0, 'a'], [1, 'b']]
11.4. Use case#
#All the if conditions can be applied since it is list comprehension
11.4.1. Getting even indexed values#
Note:It is based on index not actual values
list=[11,13,12,14,15,76,89]
11.4.2. Get the index only if index==even#
[(i,j) for i,j in enumerate(list) if i%2==0]
[(0, 11), (2, 12), (4, 15), (6, 89)]
11.4.3. Get the index only if value= 76#
[i for i,j in enumerate(list) if j==76]
[5]