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
  • 1
    Do you want to preserve duplicate elements?
    – Sede
    Commented Mar 10, 2016 at 19:19
  • list(set(Lista) - set(Listb))
    – pp_
    Commented Mar 10, 2016 at 19:21

2 Answers 2

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'}
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']