How to get the index number inside a for loop

Viewed 49

This is my dataset:

dataset = [['A','B','C], ['D','E','F']]

I want the INDEX in this for loop.

for x in dataset:
  print ?????

I also tried this and many other things:

print(x.index())
prit(index(x))
etc..

All return errors.

2 Answers

Use enumerate as follows :

for ind, x in enumerate(dataset) :
  print(ind)

To make the answer more understandable because i'm not a fan of 'use this function it just works' (it's efficient but usually lacks teaching) the enumerate funtions works just like:

#values = your list
index = 0
for value in values:
    print(index, value)
    index += 1
Related