You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Python列表推导式触发IndexError,求错误原因及解决方法

Why You're Getting IndexError and How to Fix It

Let’s break down exactly what’s going on here and how to resolve it:

First, let’s recap your code and the error trigger:

a = [1,2,1,5]
b = [1,1,5]
c = [a[index] for index in b]
print(c)

You’re hitting IndexError: list index out of range because your code is trying to use every element in b as an index to pull values from a. Here’s the problem:

  • List a has 4 elements, so valid indices for a are 0, 1, 2, 3 (Python uses zero-based indexing).
  • The third element in b is 5—there’s no a[5] because a only goes up to index 3. That’s why the error occurs.

How to Fix It

The solution depends on what you actually intended to do. Here are the most common scenarios:

Scenario 1: You meant to use valid indices for a

If b was supposed to contain only valid indices for a, correct the invalid value (5) to something between 0 and 3. For example:

a = [1,2,1,5]
b = [1,1,3]  # Changed 5 to 3 (the index of 5 in a)
c = [a[index] for index in b]
print(c)  # Output: [2, 2, 5]

Scenario 2: You wanted to filter elements from a that exist in b

If your goal was to get all elements in a that are also present in b (not use b as indices), adjust the list comprehension to check membership instead:

a = [1,2,1,5]
b = [1,1,5]
# Convert b to a set for faster membership checks
b_set = set(b)
c = [element for element in a if element in b_set]
print(c)  # Output: [1, 1, 5]

Scenario 3: You want to skip invalid indices gracefully

If you need to keep b as-is but avoid crashing, add a condition to only use valid indices:

a = [1,2,1,5]
b = [1,1,5]
c = [a[index] for index in b if 0 <= index < len(a)]
print(c)  # Output: [2, 2]

内容的提问来源于stack exchange,提问作者Haseef Azhaan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:22:47