Home > database >  remove items using two list
remove items using two list

Time:11-03

I have two lists and i want remove some items from the first list. I don't understand why my code doesn't work. My input:

l0=['Localisation level 2 AM', 'Rang', 'Localisation level 3 AM', 'WP Level 2', 'WP Level 3', 'Unnamed: 5', 'Unnamed: 6']
l1=['Localisation level 2 AM', 'Localisation level 3 AM', 'WP Level 2', 'WP Level 3']

I try to do this but 'WP Level 2' still in the first list l0:

for e in l0:
   if e in l1:
      l0.remove(e)
print(l0)
['Rang', 'WP Level 2', 'Unnamed: 5', 'Unnamed: 6']

CodePudding user response:

For your information, if the order doesn't matter, you can use set to accomplish what you want:

>>> set(l0).difference(l1)
{'Rang', 'Unnamed: 5', 'Unnamed: 6'}

CodePudding user response:

Copy your l0 list to another variable. You are removing items while you iterating through a list, so there is your problem. Also, l.remove should look like l0.remove, because l is not defined import copy l0=['Localisation level 2 AM', 'Rang', 'Localisation level 3 AM', 'WP Level 2', 'WP Level 3', 'Unnamed: 5', 'Unnamed: 6'] l1=['Localisation level 2 AM', 'Localisation level 3 AM', 'WP Level 2', 'WP Level 3']

l00 = copy.copy(l0)
for e in l0:
   if e in l1:
      print(e)
      l00.remove(e)
print(l00)

CodePudding user response:

As others have said, it's a bad idea to modify a list while iterating over it.

The pythonic way to deal with this is to construct a new list and assign it back to l0:

l0 = [item for item in l0 if not item in l1]

CodePudding user response:

l0=['Localisation level 2 AM', 'Rang', 'Localisation level 3 AM', 'WP Level 2', 'WP Level 3', 'Unnamed: 5', 'Unnamed: 6']
l1=['Localisation level 2 AM', 'Localisation level 3 AM', 'WP Level 2', 'WP Level 3']

# for e in l0:
#    if e in l1:
#       l0.remove(e)
# print(l0)

l2 = []
for x in l0:
    if x not in l1:
        l2.append(x)
l0 = l2
print(l0)

['Rang', 'Unnamed: 5', 'Unnamed: 6']

CodePudding user response:

See https://sopython.com/canon/95/removing-items-from-a-list-while-iterating-over-the-list/

The reason for this is that the iterator does not know that a list element was removed, and happily advances to the next item.

A better solution would be to use a list comprehension:

l0 = [e for e in l0 if not e in l1]
print(l0)

or to iterate reversely:

for e in reversed(l0):
        if e in l1:
            l0.remove(e)

or to iterate over a copy of the list:

for e in list(l0):
        if e in l1:
            l0.remove(e)
  • Related