0

I have two lists Lista and Listb ,am trying to update Lista by removing all the elements from it present in Listb,how do I do that?

Lista = ['1535408', '1527610', '1532634']
Listb = ['1527610', '1532634']

EXPECTED OUTPUT:-
 Lista = ['1535408']

2 Answers2

1

Make a set from the elements of Listb (for the O(1) lookup time). Use a list comprehension and a reassignment to do the filtering.

>>> Lista = ['1535408', '1527610', '1532634']
>>> Listb = ['1527610', '1532634']
>>> b_items = set(Listb)
>>> Lista = [item for item in Lista if item not in b_items]
>>> Lista
['1535408']
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

Using list comprehensions

>>> Lista = ['1535408', '1527610', '1532634']
>>> Listb = ['1527610', '1532634']
>>> Lista = [item for item in Lista if item not in Listb]
['1535408']

If you don't want to preserve duplicates elements then:

>>> set(Lista).difference(Listb)
{'1535408'}
styvane
  • 59,869
  • 19
  • 150
  • 156