1

I have a two dimensional list and for every list in the list I want to print its index and for every element in each list I also want to print its index. Here is what I tried:

l = [[0,0,0],[0,1,1],[1,0,0]] def Printme(arg1, arg2): print arg1, arg2 for i in l: for j in i: Printme(l.index(i), l.index(j)) 

But the output is:

0 0 # I was expecting: 0 0 0 0 # 0 1 0 0 # 0 2 1 0 # 1 0 1 1 # 1 1 1 1 # 1 2 2 0 # 2 0 2 1 # 2 1 2 1 # 2 2 

Why is that? How can I make it do what I want?

1
  • It won't work that way because list.index short circuits upon finding the first value equal to your search value. Commented Jun 16, 2013 at 9:47

2 Answers 2

1

Help on list.index:

L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present.

You should use enumerate() here:

>>> l = [[0,0,0],[0,1,1],[1,0,0]] for i, x in enumerate(l): for j, y in enumerate(x): print i,j,'-->',y ... 0 0 --> 0 0 1 --> 0 0 2 --> 0 1 0 --> 0 1 1 --> 1 1 2 --> 1 2 0 --> 1 2 1 --> 0 2 2 --> 0 

help on enumerate:

>>> print enumerate.__doc__ enumerate(iterable[, start]) -> iterator for index, value of iterable Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ... 
Sign up to request clarification or add additional context in comments.

2 Comments

@AshwiniChaudhary why not just do help(enumerate) it's much simpler for beginners
@jamylak well the only reason is output of enumerate.__doc__ is easier to copy than the output of help(enumerate) which starts Vi. Though on IPython I usually prefer enumerate?.
0

.index(i) gives you the index of the first occurrence of i. Therefore, you always find the same indices.

Comments