Python Forum

Full Version: Problem with comparing list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to compare the elements of two list and the code to return True if all of the elements in the second list is present in the first. The code is:
list_a = [25,15,40,40,10]
list_b = [40,40,10]

if all(i for i in list_b) in list_a:
    print('true')
else:
    print('false')
When run, the code returns False despite all of the elements in list_b being present in list_a.

Would appreciate some help here.

Thanks
The all function doesn't work like that - it returns True if all the values are truthy, which for integers means non-zero. So, your call to all returns True and the value True is not in list_a, so execution enters the else branch.

Probably the most natural way to do what you want is to turn the lists into sets and use one of the set operations (see, e.g. docs).
list_b is shorter. Checking if all elements of list_b are in list_a:

list_a = [25,15,40,40,10]
list_b = [40,40,10]

if all(b in list_a for b in list_b):
    print('All elements of list_b are in list_a')
else:
    print('Not all elements of list_b are in list_a')
If you use the set theorie, it's easier:
list_a = [25,15,40,40,10]
list_b = [40,40,10]
if set(list_b).issubset(list_a):
    print("set_b is a subset of set_a")
else:
    print("set_b is not a subset of set_a")
A set contains only unique elements.
The order of elements is not preserved.