-1

I have a list in python 2.7 and I want to remove any items from it that exist in another list. The loop seems to stop short and I am not sure why it only deletes b and not b and c from lt_sub?

bad = ['b','c']

lt = ['a','b','c']
lt_sub = lt
for l in lt:
    if l in bad:
        lt_sub.remove(l)
print lt_sub
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
winteralfs
  • 459
  • 6
  • 25
  • 1
    Do `lt_sub = lt[:]` instead, that way you're dealing with two lists, and not with a single one like in your case. – ipaleka Jul 02 '19 at 01:02

1 Answers1

2

When you assign lt_sub = lt as so, you are creating a reference to lt, not a copy. When you iterate through lt in the for loop, once you remove l, lt has no more entries in the loop (as it has now been reduced to a size of 2, and you have iterated twice).

To fix, have lt_sub be a separate list, see here for an explanation.

wriuhasdfhvhasdv
  • 474
  • 4
  • 20