Skip to content
Advertisement

Checking if list element in list of lists and returning sublist

I have two lists

list1 = ['B', 'C', 'D']
list2 = [['1', 'A'], ['2', 'B'], ['3', 'D'], ['5', 'C']]

and want to return those sublistst of list2 that contain elements of list1. So far I tried using any:

result = []

for l2 in list2:
    if any (item in l2 for item in list1):
        result.append(l2)

and a naive approach

for l2 in list2:
    for l1 in l1:
        if l1 in l2:
            result.append(l2)

But I only managed to repeat empty list. The result should be

result = [['2', 'B'], ['5', 'C']]

Not sure, where I’m going wrong. Is there maybe a way using list comprehensions or mixing list comprehensions and ‘any’ function?

Advertisement

Answer

What you have looks correct and works for me locally too:

for l2 in list2:
    if any (item in l2 for item in list1):
        result.append(l2)

It returns [['2', 'B'], ['3', 'D'], ['5', 'C']] which is the expected result right?

Also note that you can speed up your implementation by changing list1 into a set list1 = set(['B', 'C', 'D']) and changing the if condition to if any (item in list1 for item in l2):.
This is because item in list1 is much faster if list1 is a set than a list. That’s because set uses a hashmap under the hood the quickly accesss elements.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement