0

Trying to troubleshoot this code and am getting a bizarre output. Can someone explain why the outermost for loop is not running for i=2? Thanks!

For context, the code was written to try to delete all values in b from a, including all repeats (i.e. a=[1,2,2], b=[2] should output [1]). I know there are more efficient ways to do it I just am confused why this doesn't work.

Code:

def arrayfunc(a,b):
    list = a
    for i in a:
        print(i)
        for j in b:
            if i == j:
                list.remove(j)
    print(a)

arrayfunc([1,2,3],[1])

Output

1
3
[2, 3]

1 Answers1

1

You need to copy the list a into list (although you should use a name other than list since it's a built-in) as list=a.copy() or list=a[:]. Currently you are just pointing list to a, so when you modify list you also modify a.

See this answer: What is the difference between a = b and a = b[:]?

jpf
  • 1,447
  • 12
  • 22