Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to check if a list is present in a list of lists

Tags:

python

list

set

I have a list

a=[[1,2,3,4,5,6],[7,8,9,10,11,12]]   

What is the fastest way to check if any list in a is present in another list of lists b, where

b=[[5, 9, 25, 31, 33, 36],[7,8,9,10,11,12],[10, 13, 22, 24, 33, 44]]

If any list in a is present in b, I would like to remove it. I'm currently using this code:

for each in a:
    for item in b:
        if set(each).issubset(item)
            a.remove(each)

This works but is quite slow when working with large lists so was wondering if there's a better way. The above code gives me the following result:

print(a)
[[1, 2, 3, 4, 5, 6]]

I am not worried about order, for example if a list in ais [1,2,3,4,5,6] I want it to be removed if there exist a list [1,2,3,4,5,6] or [3,4,1,6,2,5] etc in list b.

like image 567
West Avatar asked May 24 '18 13:05

West


People also ask

How do you check if a list is in a list of lists in Python?

Method 1: Using isinstance() With any() methods that will help us to check the list if it is nested or not. What is this? ◉ isinstance is a built-in method in Python which returns True when the specified object is an instance of the specified type, otherwise it returns False .

How do you check if a list is present in another list in Python?

Given two lists A and B, write a Python program to Check if list A is contained in list B without breaking A's order. A more efficient approach is to use List comprehension. We first initialize 'n' with length of A. Now use a for loop till len(B)-n and check in each iteration if A == B[i:i+n] or not.

How do you check if an element appears in a list?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.


1 Answers

Using a list comprehension with set.

Ex:

a=[[1,2,3,4,5,6],[7,8,9,10,11,12]]  
b=[[5, 9, 25, 31, 33, 36],[7,8,9,10,11,12],[10, 13, 22, 24, 33, 44]]

setA = set(map(tuple, a))
setB = set(map(tuple, b))

print([i for i in setA if i not in setB])

Output:

[(1, 2, 3, 4, 5, 6)]
like image 111
Rakesh Avatar answered Sep 25 '22 06:09

Rakesh