Susanta Dutta
Susanta Dutta

Reputation: 449

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

Upvotes: 0

Views: 38

Answers (4)

Adon Bilivit
Adon Bilivit

Reputation: 27201

You could use the if / else construct which will be easier to read / maintain than some of the rather esoteric suggestions already made:

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

L3 = []

for e in L1:
    for f in L2:
        if e in f:
            break
    else:
        L3.append(e)

print(L3)

Output:

['apple', 'cherry']

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 102519

Here is another option using difference

list({*L1}.difference(x for y in L2 for x in L1 if x in y))

# ['apple', 'cherry']

Upvotes: 1

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9213

Using simple for:

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

result = []
for x in L1:
    match = False
    for y in L2:
        if x in y:
            match = True
            break
    if not match:
        result.append(x)

print(result) #['apple', 'cherry']

With list comprehension: [x for x in L1 if not any(x in y for y in L2)]

Upvotes: 1

Sash Sinha
Sash Sinha

Reputation: 22473

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

Upvotes: 2

Related Questions