-2

I would like to find the corresponding item in a list but the code below seems to find the corresponding item and then moves on item further as shown:

a = [1,2,3,4]
b = [5,6,7,8]
for i in a:
    if i == 1:
       print b[i]

Which gives me:

6

When I thought it should print:

5

In which case I'm now having to write:

print b[i-1]
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
python_starter
  • 1,509
  • 1
  • 11
  • 18

4 Answers4

3

python list index starts from 0 .

when you try to iterate a list you will be getting each and every element in the list

for example:

a = [1,2,3,4]
for element in a:
    print element

will be printing [1,2,3,4]

incase if you want to get the index along with the element you should use enumerate function

for example:

a = [1,2,3,4]
for index, element in enumerate(a):
    print index, element

will be printing 0,1 where 0 is the index of 1 in list 1,2 2,3 3,4

in you program you can use enumerate to achieve what you want

a = [1,2,3,4]
b = [5,6,7,8]
for index, i in enumerate(a):
    if i == 1:
       print b[index]

will yield you the result you want.

sathya Narrayanan
  • 499
  • 1
  • 5
  • 16
1

Your condition is i==1, so when this is satisfied it naturally always looks up the second element (counting from 0) of b. (If the value 1 appeared at some other location in a, the workaround b[i-1] you are using would fail.)

I suspect what you want is

a = [1,2,3,4]
b = [5,6,7,8]
print b[a.index(1)]

(note that this avoids the unnecessary for loop). But your question isn't clear.

snadathur
  • 11
  • 1
  • Not really a general answer and clearly not what the OP wanted. – erip Dec 09 '15 at 12:15
  • 1
    Assuming that `a` contains the value being searched for (in this case, `1`) my answer achieves exactly the same thing as that in the accepted answer, but it will be faster and is more Pythonic. So I don't understand your comment. – snadathur Dec 09 '15 at 14:35
  • `a = [1,2,3,4,1,2]; b = [5,6,7,8,10000,6,3]; print b[a.index(1)]` Doesn't work. – erip Dec 09 '15 at 20:51
1

In your code, i==1 corresponds to the 0th element of a.

a.index(i) gives us the index with which we can print the corresponding element of b.

a = [1,2,3,4]
b = [5,6,7,8]

for i in a:
    if i == 1:
       print b[a.index(i)]

This would print the first element of b i.e 5

KartikKannapur
  • 973
  • 12
  • 19
0

The reason, as everyone has mentioned, is because Python lists are 0-based.

When i == 1, you then print b[i] == b[1] == 2

To get the index, you need to use enumerate, which returns the index then the element at that index.

Here's how you should use it.

   for idx, elem in enumerate(a):
     if elem == 1:
       print b[idx]
erip
  • 16,374
  • 11
  • 66
  • 121