Compare two lists for content

Question:

I have the given the following two lists:

list1 = ['', '', 'void KL15 ein', '{', '}', '', 'void Motor ein', '{', '}', '']
and
list2 = ['KL15 ein', 'Motor ein']

Now I want to find out if the a value from the second list 'KL15 ein' is also in the first list (as a void function).
Do I need to extract the value 'KL15 ein' from both lists to compare it or is there another way to do it without extracting (via splitting and access the list) the values?
Edit: I noticed that I need variables (can’t use ‘KL15 ein’ as a string), e.g: if the value from list1 is also listed in list 2

Asked By: Markus

||

Answers:

I think you can use the issubset() or all() function.

issubset()

if(set(subset_list).issubset(set(large_list))):
    flag = 1
 
# printing result
if (flag):
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")

or all() function

if(all(x in test_list for x in sub_list)):
    flag = 1
 
# printing result
if (flag):
    print("Yes, list is subset of other.")
else:
    print("No, list is not subset of other.")

Answered By: Adithya.K

You can do something like

#l1 is list 1, l2 is list 2
if 'void KL15 ein' in l1 and 'KL15 ein' in l2:
  #logic for if true
else:
  #logic for if not true
Answered By: Sister Coder

First, get the set of void function names from the first list by checking which strings start with "void " and then stripping away that bit. Then, you can use a simple list comprehension, all expression or for loop to check which of the elements in the second list are in that set.

lst1 = ['', '', 'void KL15 ein', '{', '}', '', 'void Motor ein', '{', '}', '']
lst2 = ['KL15 ein', 'Motor ein']                                        
void_funs = {s[5:] for s in lst1 if s.startswith("void ")}              
res = [s in void_funs for s in lst2]                                          
# [True, True]

Or as a loop with a condition:

for s in lst2:
    if s in void_funs:
        # do something
Answered By: tobias_k
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.