Reputation: 1
I keep getting a "list index out of range" error, but don't know why. Can someone help?
arr = []
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
for x in range (x+1):
for y in range(y+1):
for z in range(z+1):
arr.append([x,y,z])
for i in range(len(arr)):
if (arr[i][0] + arr[i][1] + arr[i][2] == n):
del arr[i]
print(arr)
Upvotes: 0
Views: 43
Reputation: 54148
That is because you iterate over the len of an array, but that len is computed and stored at the beginning, it isn't update. Let's say the array if of len 5, the loop generates 0,1,2,3,4
but if you delete an item during the loop, when doing arr[4]
it'll fail
The best solution is to keep interesting items, not delete the others, whether with another array, or a list comprehension. Also you can iterate of the values of an array, not on indices
# new array
new_vals = []
for v in arr:
if sum(v) != n:
new_vals.append(v)
# list comprehension
arr = [v for v in arr if sum(v) != n]
Upvotes: 0
Reputation: 71454
It's better to build a list like this as a comprehension, where you can filter the elements as you build the list rather than having to go back and try to extract them after the fact:
x, y, z, n = (int(input()) for _ in range(4))
arr = [
[i, j, k]
for i in range(x+1)
for j in range(y+1)
for k in range(z+1)
if i + j + k != n
]
Upvotes: 0
Reputation: 354
This is happening because you're mutating your list as you traverse through it. In your specific example, you would actually be better off creating a new list from the old list. In this example:
arr = [x for x in arr if (x[0] + x[1] + x[2] != n)]
EDIT: In addition to the comment about the scope of this activity relative to main.
Upvotes: 1