Reputation: 155
I have two arrays in python. I want to remove all the elements that present in first array. Here an example of arrays:
array1 =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 2, 4, 6, 8, 10, 3, 6, 9, 4, 8, 5, 10, 6, 7, 8, 9, 10, 11]
The result would be:
array2 = []
Here what I've done:
for x in array1:
for y in array2:
if x==y:
array2.remove(x)
print (array2)
But I'm seeing [10] as result. Why? And how to fix this?
Upvotes: 1
Views: 1192
Reputation: 1613
Consider the following example of unexpected behavior when modifying a list while iterating over it:
a = [10, 10]
for x in a:
if x == 10:
a.remove(x)
print 'item removed'
After the first removal, the second 10
element becomes the first element of the list and x
has already pointed to the first element (position 0). Thus the second iteration will never occur.
Upvotes: 0
Reputation: 317
def diff(first, second):
return [item for item in first if item not in second]
Upvotes: 0
Reputation: 884
I'm guessing the issue has to do with how you are looping and removing items in the list, making the program skip over the third 10
.
You can use a quick list comprehension to solve the issue:
array3 = [i for i in array2 if i not in array1]
This is basically a simpler way of typing:
array3 = []
for i in array2:
if i not in array1:
array3.append(i)
Additionally, you probably wouldn't want to use sets. For example:
array1 = [1, 2, 3]
array2 = [1, 2, 3, 3, 4, 4, 5, 6]
array3 = list(set(array2) - set(array1))
array3
will only contain [4, 5, 6]
, rather than [4, 4, 5, 6]
, since set
s cannot contain duplicates.
Upvotes: 1