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

遍历数组时触发IndexError: list index out of range错误求助

Fixing IndexError: list index out of range When Iterating Over Arrays

Hey there! Let's break down why you're hitting this super common error and how to fix it—no need to pull your hair out over it.

Common Causes & Examples

Let's walk through the most frequent scenarios that trigger this error:

  • Hardcoding index values or using an incorrect loop range
    If you're using a fixed number in your loop (like range(5)) instead of tying it to your list's actual length, you'll run into trouble when the list is shorter than that number. For example:

    fruits = ["apple", "banana", "cherry"]
    # This loops 5 times, but fruits only has 3 elements
    for i in range(5):
        print(fruits[i])  # Fails when i=3 and 4
    
  • Modifying the list's length while iterating
    If you add or remove elements from the list mid-loop, the original length you based your loop on no longer matches the current list. Here's a classic mistake with pop():

    numbers = [1, 2, 3, 4]
    for i in range(len(numbers)):
        if numbers[i] % 2 == 0:
            numbers.pop(i)  # Removes element, making the list shorter
    # By the time i reaches 3, the list only has 2 elements left—boom, error
    
  • Using the list length as an index
    Remember, list indices start at 0! The last element's index is always len(list) - 1. Using len(list) directly will always be out of bounds:

    colors = ["red", "green"]
    print(colors[len(colors)])  # len(colors) is 2, but max index is 1
    
  • Mistakes with nested lists (2D arrays)
    If you're working with a list of lists, make sure each sub-list has enough elements for the index you're trying to access:

    matrix = [[1, 2], [3]]
    for row in matrix:
        print(row[1])  # The second row only has one element—index 1 doesn't exist
    

Quick Fixes & Best Practices

  • Iterate over elements directly (not indices)
    This is the simplest way to avoid index issues entirely:
    for fruit in fruits:
        print(fruit)
    
  • If you need indices, use range(len(your_list))
    This ensures your loop only runs for the exact number of elements in the list. Just don't modify the list while doing this!
  • If you must modify the list, iterate over a copy
    Make a duplicate of the list first so your loop doesn't get thrown off by length changes:
    numbers = [1, 2, 3, 4]
    # Iterate over a copy of the list
    for num in numbers.copy():
        if num % 2 == 0:
            numbers.remove(num)
    
  • Debug with print statements
    When stuck, print the current index and the list's length at each step to see exactly where things go wrong:
    for i in range(len(numbers)):
        print(f"Current index: {i}, List length: {len(numbers)}")
        print(numbers[i])
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:55:32