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?

Martijn Pieters
1.1m324 gold badges4.2k silver badges3.4k bronze badges
asked Jun 16, 2013 at 9:45
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]), ...
answered Jun 16, 2013 at 9:46
2
  • @AshwiniChaudhary why not just do help(enumerate) it's much simpler for beginners Commented Jun 16, 2013 at 10:36
  • @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?. Commented Jun 16, 2013 at 10:43
0

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

answered Jun 16, 2013 at 9:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.