Skip to content Skip to sidebar Skip to footer

Python Removing Items From A List That Exist In Another List But Keeping Duplicates That Aren't In That Intersect

I'm using python to try and remove items that intersection from another list. So below is what I have. letter = ['a', 'a', 'i', 'd', 'e', 'i', 'a', 'b', 'b', 'c', 'o', 'g', 'a', '

Solution 1:

>>> letter = ['a', 'a', 'i', 'd', 'e', 'i', 'a', 'b', 'b', 'c', 'o', 'g', 'a', 'f', 'f', 'i', 'g', 'i' ]
>>> cons = ['b','c','d', 'f', 'g']

>>> [x for x in letter if x notin cons]
['a', 'a', 'i', 'e', 'i', 'a', 'o', 'a', 'i', 'i']

a simple list comprehension will do the trick?

EDIT:

As ShadowRanger said, it would improve performance (mostly for larger data sets than these) to convert cons to a set:

cons = set(cons)

then to go into the list comp. This is better because sets are hashed and makes getting items/checking for items in it way faster

Solution 2:

A list comprehension is better, but your original code works if we just remove one line:

>>> letter = ['a', 'a', 'i', 'd', 'e', 'i', 'a', 'b', 'b', 'c', 'o', 'g', 'a', 'f', 'f', 'i', 'g', 'i' ]
>>> cons = ['b','c','d', 'f', 'g']
>>> for i in letter[:]:
... if i in cons:
...          letter.remove(i)
...
>>> letter
['a', 'a', 'i', 'e', 'i', 'a', 'o', 'a', 'i', 'i']

Post a Comment for "Python Removing Items From A List That Exist In Another List But Keeping Duplicates That Aren't In That Intersect"