-1

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]

  • 3
    You've got an error? or the result is not the same as your expected? Please give these information on your question – Toan Quoc Ho Sep 04 '19 at 00:16
  • 2
    Welcome to SO! It's not recommended to remove an item from a list while iterating over it. Please provide more information about what your inputs and outputs are and why the current code isn't doing what you want. Thanks! – ggorlen Sep 04 '19 at 00:18
  • Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – wjandrea Sep 04 '19 at 00:23
  • The result was not what I expected. It should remove all values from a that are in b, so the result should be a = [1], instead I get a = [1,2] – Josh Sterken Sep 04 '19 at 03:58

4 Answers4

0

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)
MAO3J1m0Op
  • 423
  • 3
  • 14
yu2
  • 126
  • 4
0

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)

Ranga
  • 620
  • 1
  • 7
  • 9
0

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.

Hiadore
  • 686
  • 3
  • 15
0

you can just do a list comprehension

new = [c for c in a if c not in b]
Derek Eden
  • 4,403
  • 3
  • 18
  • 31