简体   繁体   中英

Why am I getting this IndexError

a = [1,2,1,5]

b = [1,1,5]

c = [a[index] for index in b]  
print(c)

and I got this error:

IndexError
Traceback (most recent call last)
<ipython-input-158-e03093b57c86> in <module>

    2 b=[1,1,5]
      3 index=0
----> 4 c=[a[index] for index in b]
      5 c

<ipython-input-158-e03093b57c86> in <listcomp>(.0)

    2 b=[1,1,5]
      3 index=0
----> 4 c=[a[index] for index in b]
      5 c

IndexError: list index out of range

I believe you wanted to do this: (Slight modification of your code)

c = [a[index] for index in range(len(b))]

This iterates over the length of list b, which is [0, 1, 2] as len(b) = 3. And these are valid indexes for list a.

In the above implemenation, the list you are iterating over is [1, 1, 5]. And a[5] does not exist since list a has only 4 elements.

Hope this helps!

The reason you are getting this is error is because your list b has got the number 5 and your list a is of length 5 and hence has a maximum index of 4, since indexing starts from 0.

So when you try and grab the value from list a at index 5 , there is no such value which results in the error: list index out of range

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM