Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to keep elements of a list based on another list [duplicate]

I have two lists looking like:

list1 = ['a','a','b','b','b','c','d','e','e','g','g']

list2 = ['a','c','z','y']

What I want to do is to keep all those elements of list1 that are also in list2. the outcome should be:

outcome= ['a','a','c']
like image 826
Blue Moon Avatar asked Nov 28 '22 14:11

Blue Moon


1 Answers

Using in operator, you can check whether an element is in a seqeunce.

>>> list2 = ['a','c','z','y']
>>> 'x' in list2
False
>>> 'y' in list2
True

Using list comprehension:

>>> list1 = ['a','a','b','b','b','c','d','e','e','g','g']
>>> list2 = ['a','c','z','y']
>>> [x for x in list1 if x in list2]
['a', 'a', 'c']

But x in list is not efficient. You'd better convert list2 to a set object.

>>> set2 = set(list2)
>>> [x for x in list1 if x in set2]
['a', 'a', 'c']
like image 161
falsetru Avatar answered Dec 04 '22 03:12

falsetru