user2489716
user2489716

Reputation:

Get index of element in list in list

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?

Upvotes: 1

Views: 577

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

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]), ...

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336468

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

Upvotes: 0

Related Questions