3

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
1
  • I may be wrong, but wouldn't this just be lines[1]? For each item in lines[0], you're wanting to find the index of that occurrence of the item (not the first occurrence), and return the corresponding item from lines[1]. But the sequence of indices that will generate is just 0, 1, 2, ... Commented Dec 23, 2013 at 22:11

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I only wanted the value of the next sublist, from the index of the curent sublist. Once I have reached last substring I would get an error, hence why I used len(lines)-1.
0

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]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.