Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all items in a list are there in another list?

Tags:

I have two lists say

List1 = ['a','c','c'] List2 = ['x','b','a','x','c','y','c'] 

Now I want to find out if all elements of List1 are there in List2. In this case all there are. I can't use the subset function because I can have repeated elements in lists. I can use a for loop to count the number of occurrences of each item in List1 and see if it is less than or equal to the number of occurrences in List2. Is there a better way to do this?

Thanks.

like image 762
pogo Avatar asked Feb 28 '13 23:02

pogo


People also ask

How do you check if all elements in list are in another list?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.

How do you see if an item in a list is in another list Python?

To check if the item exists in the list, use Python “in operator”. For example, we can use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, then it returns False.


1 Answers

When number of occurrences doesn't matter, you can still use the subset functionality, by creating a set on the fly:

>>> list1 = ['a', 'c', 'c'] >>> list2 = ['x', 'b', 'a', 'x', 'c', 'y', 'c'] >>> set(list1).issubset(list2) True 

If you need to check if each element shows up at least as many times in the second list as in the first list, you can make use of the Counter type and define your own subset relation:

>>> from collections import Counter >>> def counterSubset(list1, list2):         c1, c2 = Counter(list1), Counter(list2)         for k, n in c1.items():             if n > c2[k]:                 return False         return True     >>> counterSubset(list1, list2) True >>> counterSubset(list1 + ['a'], list2) False >>> counterSubset(list1 + ['z'], list2) False 

If you already have counters (which might be a useful alternative to store your data anyway), you can also just write this as a single line:

>>> all(n <= c2[k] for k, n in c1.items()) True 
like image 75
poke Avatar answered Sep 22 '22 22:09

poke