Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with comparing list
#1
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
Reply
#2
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).
Reply
#3
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Comparing List values to get indexes Edward_ 7 1,083 Jun-09-2023, 04:57 PM
Last Post: deanhystad
  Problem with "Number List" problem on HackerRank Pnerd 5 2,034 Apr-12-2022, 12:25 AM
Last Post: Pnerd
  comparing 2 dimensional list glennford49 10 4,037 Mar-24-2020, 05:23 PM
Last Post: saikiran
  Looping through dictionary and comparing values with elements of a separate list. Mr_Keystrokes 5 3,832 Jun-22-2018, 03:08 PM
Last Post: wavic
  Get the correct value when comparing with the list chris0147 8 4,741 Aug-09-2017, 01:21 AM
Last Post: chris0147
  Create a new list by comparing values in a list and string DBS 2 3,484 Jan-14-2017, 07:59 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020