Search code examples
pythonlistlist-comprehension

Eliminating list elements having string from another list


I'm trying to a get a subset of elements of L1, which do not match with any element of another list

>>> L1 = ["apple", "banana", "cherry", "date"]
>>> L2 = ["bananaana", "datedate"]
>>> 

For instance, from these two lists, I want to create a list ['apple', 'cherry']

>>> [x for x in L1 for y in L2 if x in y]
['banana', 'date']
>>>

The above nested list comprehension helps to get element which matches, but not other way

>>> [x for x in L1 for y in L2 if x not in y]
['apple', 'apple', 'banana', 'cherry', 'cherry', 'date']  
>>>

          ^^^^^^^^   I was expecting here ['apple', 'cherry']

Solution

  • Consider utilizing any:

    >>> L1 = ["apple", "banana", "cherry", "date"]
    >>> L2 = ["bananaana", "datedate"]
    >>> [x for x in L1 if not any(x in y for y in L2)]
    ['apple', 'cherry']