Reputation: 443
I recently asked a question here: How do I find if an int is in array of arrays? and the solution works well. I'm trying to write code which will remove an int from an array if another array doesn't contain it. The loop I'm trying to use is:
for index in range(len(numbers)):
if not any(numbers[index] in elem[:2] for elem in numbers2):
numbers.remove(numbers[index])
Say numbers = [1, 2, 4]
and numbers2 = [[4,5,6], [2,8,9]]
then after the loop, numbers[] should be numbers = [2, 4]
. The above loop however keeps producing the error exceptions.IndexError: list index out of range
but I can't see why the error keeps being thrown. Could anyone help with this issue?
Upvotes: 0
Views: 616
Reputation: 3031
Create a temporal list and save the positions you want to remove, then after all iterating is done delete the items in those positions. Remember to delete in reverse order to preserve index numbers while deleting.
to_remove = []
for index, number in enumerate(numbers):
if not any(number in elem[:2] for elem in numbers2):
to_remove.append(index)
for index in reversed(to_remove):
del numbers[index]
Upvotes: 1
Reputation: 500257
The problem is that len(numbers)
in only evaluated once, at the start of the loop.
I would rewrite the whole thing like so:
In [12]: numbers = [1, 2, 4]
In [13]: numbers2 = [[4,5,6], [2,8,9]]
In [15]: n2s = set(reduce(operator.add, (n[:2] for n in numbers2)))
In [17]: [n for n in numbers if n in n2s]
Out[17]: [2, 4]
Upvotes: 4