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

如何从列表list1中移除存在于列表list2中的子列表并避免索引越界问题?

Fixing the Index Error and Filtering List Elements

The issue with your original code stems from two key problems:

  • You’re iterating over the length of list2 instead of list1, which leads to trying to access indices in list1 that don’t exist (since list1 is shorter than list2 in your example).
  • Even if you iterated over list1’s length, modifying the list while iterating forward causes index shifting—this can skip elements or trigger out-of-bounds errors as the list shrinks.

A clean, safe way to achieve your goal is to create a new list containing only elements from list1 that are not present in list2. Here’s how to do it with a list comprehension:

list1 = [[6, 0, 3, 1, 5, 7, 8, 2, 4], [1, 5, 0, 4, 6, 2, 7, 8, 3]]
list2 = [[1, 5, 2, 4, 6, 0, 7, 8, 3], [1, 5, 0, 4, 6, 2, 7, 8, 3], [1, 8, 2, 4, 0, 6, 7, 5, 3]]

# Filter list1 to keep elements not found in list2
list1 = [item for item in list1 if item not in list2]

print(list1)  # Output: [[6, 0, 3, 1, 5, 7, 8, 2, 4]]

Why this works:

  • List comprehensions are purpose-built for filtering tasks: they loop through each element in list1, check if it’s absent from list2, and include it in the new list only if the condition holds.
  • By creating a new list instead of modifying the original while iterating, you avoid all index-related bugs entirely.

If you need to modify list1 in-place (optional):

If you prefer to update the original list without creating a new one, iterate backwards over list1’s indices. This way, removing elements doesn’t affect the indices of the items you haven’t checked yet:

# Iterate from the last index to the first
for i in range(len(list1)-1, -1, -1):
    if list1[i] in list2:
        list1.pop(i)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 16:37:44