遍历数组时触发IndexError: list index out of range错误求助
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 (likerange(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 4Modifying 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 withpop():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, errorUsing the list length as an index
Remember, list indices start at 0! The last element's index is alwayslen(list) - 1. Usinglen(list)directly will always be out of bounds:colors = ["red", "green"] print(colors[len(colors)]) # len(colors) is 2, but max index is 1Mistakes 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

