user2770624
user2770624

Reputation: 393

Python - Index of duplicate item in list

I am trying to find the index of a sub-list return the value with the same index of another sub-list. I keep on running into a problem when I have duplicates, since it just returns the lowest index.

lines = [ [ 1 , 1], [3, 4] ]
x = 0
while x < (len(lines)-1):
    for ch in lines[x]:
        print lines[x+1][lines[x].index(ch)]
    x += 1

I wanted to get an output of

3
4

but I am getting

3
3

Upvotes: 3

Views: 1437

Answers (3)

C.B.
C.B.

Reputation: 8346

index() finds the first occurence of the passed element of the list, so whenever you call [1,1].index[1], you will always get 0.

If your goal is to simply access the item of list b from the index in list a-

a = [1,1]
b = [3,4]
for x in range(0,len(a)):
    print b[x]

Upvotes: 0

Frank Conry
Frank Conry

Reputation: 2716

I think I understand. In both iteration so the for loop ch is 1 so lines[x].index(ch) will be 1. Why not just loop through the second in a more straight forward fashion:

lines = [ [ 1 , 1], [3, 4] ]
x = 0
y=0
while x < (len(lines)-1):
    while y < len(lines[x]):
        print lines[x+1][y]
        y= y+1
    x = x+1

Upvotes: 1

Prewitt
Prewitt

Reputation: 33

You should change your len(lines)-1 by len(lines) in the while statement, because i think it doesnt tests all the values.

Upvotes: 0

Related Questions