Want to know why using 2 for loops wont work to delete one list from another
def array_diff(a, b):
for item in b:
for i in a:
if item == i:
a.remove(item)
a = [1,2,2] b = [2]
Want to know why using 2 for loops wont work to delete one list from another
def array_diff(a, b):
for item in b:
for i in a:
if item == i:
a.remove(item)
a = [1,2,2] b = [2]
You need to edit your function.
instead of
def array_diff(a, b):
for item in b:
for i in a:
if item == i:
a.remove(item)
try:
def array_diff(a, b):
for item in b:
for i in reversed(a):
if item == i:
a.remove(i)
As ggorlen said, it's not wise to remove items from a list while iterating through it. If you want just the items in a
that are not in b
consider using list comprehension and for extra efficiency a set. Consider:
def array_diff(a, b):
B = set(b)
return [ x for x in a if x not in B ]
Using a set allows x not in B
to be O(1) instead of O(n)
if you want to loop and delete, please try this:
def array_diff(a, b):
for item in b:
for i in a[:]:
if item == i:
a.remove(item)
a[:]
return a copy of a.