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 a
is [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
.
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 .
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.
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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With