tharvey tharvey - 4 days ago 6
Python Question

"list out of range" thrown when trying to remove rows in list of list where list[i][0] and list[i][1] == 0

I am trying to remove rows in an array that have

0
values for the first two columns. My code is:

for i in range (5680):
if games[i][0] == 0 and games[i][1] == 0:
games.pop(i)
print(games)


Putting a print statement of
games[i][0]
and
games[i][1]
in under the second line prints out a whole bunch of lines of
0
's so I know that these rows do exist.I am getting a
list out of range
error, even though games is a
5680
by
5
matrix.
No matter what I try changing the error is still thrown. Whats going on?

Answer

Trying to change an object that you are iterating through is almost always a bad idea. In your case after first pop() you have list that is already smaller than 5680. So when you get to 5679 you are already out of range.

Try this:

games = [g for g in games if g[0] != 0 or g[1] != 0]

or

games = list(filter(lambda g: g[0] != 0 or g[1] !=0, games))
Comments