Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if List contains all items from another list

Tags:

What is the easiest/fastest way to check if a list of tuples contains all the the tuples that another list does. For example:

t1 = [ (1,2), (3,4), (5,6), (7,8), (9,10), (11,12) ] t2 = [ (3,4), (11,12) ] 

would be a true case since t1 contains all the tuples in t2. I tried something like:

[i for e in t2 for i in t1 if e in i] sorted(t1) == sorted(t2) 

but this seemed to always return true. Is there a better way?

like image 923
Lance Strait Avatar asked Feb 17 '15 17:02

Lance Strait


People also ask

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

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list. count() function.

How do you check if a list contains any element of another list in Java?

ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.


2 Answers

You can use sets

t1 = [ (1,2), (3,4), (5,6), (7,8), (9,10), (11,12) ] t2 = [ (3,4), (11,12) ] set(t2).issubset(t1) # returns true  # or equivalent use '<=' so set(t2) <= set(t1) # returns true 
like image 60
Finn Avatar answered Sep 20 '22 09:09

Finn


For simplicity, you could do this:

print all(x in t1 for x in t2) 

However, that's going to search through t1 for each element in t2. That probably doesn't matter when t1 is small as in this case, but to allow for larger collections I would do this:

s1 = set(t1) print all(x in s1 for x in t2) 

or this:

print set(t1).issuperset(t2) 

This will generally be faster, since in is much faster for sets than for large lists. There's no major performance benefit in converting t2 to a set, regardless of size, so I wouldn't.

As always, it's better if you get your data in the "right" collection to begin with. So if the main purpose of t1 is to look things up in it, use a set in the first place rather than a list.

like image 31
Steve Jessop Avatar answered Sep 17 '22 09:09

Steve Jessop