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
user2489716user2489716
2 Answers 2
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
-
@AshwiniChaudhary why not just do
help(enumerate)
it's much simpler for beginnersjamylak– jamylak2013年06月16日 10:36:11 +00:00Commented Jun 16, 2013 at 10:36 -
@jamylak well the only reason is output of
enumerate.__doc__
is easier to copy than the output ofhelp(enumerate)
which startsVi
. Though on IPython I usually preferenumerate?
.Ashwini Chaudhary– Ashwini Chaudhary2013年06月16日 10:43:25 +00:00Commented Jun 16, 2013 at 10:43
.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
lang-py
list.index
short circuits upon finding the first value equal to your search value.