1

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 2

4

Use enumerate as follows :

for ind, x in enumerate(dataset) :
  print(ind)
4
  • Ok thanks a lot. Is it possible also to access the value of the item?
    – unstuck
    Commented Jul 9, 2021 at 13:42
  • LOL, I get it !
    – unstuck
    Commented Jul 9, 2021 at 13:43
  • If this answer fits you, I'd appreciate you validate it please ;)
    – RandomGuy
    Commented Jul 9, 2021 at 13:44
  • 1
    Sure, I was expecting - points like hell, because stack overflow hates begginers so I'll accept it for sure!
    – unstuck
    Commented Jul 9, 2021 at 13:45
1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.