0

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?

2
  • Sorry, you're only allowed to ask one question a day here. ;-) Commented Feb 13, 2013 at 16:51
  • You're going to have issues with removing items from a list while iterating over that same list. See this: stackoverflow.com/questions/1207406/… Commented Feb 13, 2013 at 16:52

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.