Home > Back-end >  how to find if all elements in list 1 appear in list 2
how to find if all elements in list 1 appear in list 2

Time:02-17

I have a question about a list that return True if only all elements in list1 appear in list2 otherwise you get false. What am I need to append to this code to find if all elements in list 1 appear in list 2.

def in_list(list1,list2):
    for i in list1:
        if i in list2:
            return True
        else:
            return False

print(in_list(['x',2,4.5,'a'],[5,4.5,'a','x',29,'Hello',2,75]))
print(in_list(['Y',22,4,],[5,4.5,'a','x',29,'Hello',2,75]))

i get the second false but if i append parameter to list1 that show in list2 i get True

CodePudding user response:

def in_list(list1,list2):
    for i in list1:
        if i not in list2:
            return False
    return True

Or:

    return all(item in list2 for item in list1)

CodePudding user response:

You are definitely on the right track here, but as noted in the comments you are returning in your first iteration if True, which cannot give you what you want.

Try adding a variable on the function to track this like so:

def in_list(list1,list2):
    all_in_list1 = True # make this default because of check
    for i in list1:
        if i not in list2:
            all_in_list1 = False

    return all_in_list1

CodePudding user response:

The issue here is that you only check the first element list1 to see if it's in list2 and return True/False depending on the result.

You have to check if all elements in list1 is in list2, so you could use all function:

def in_list(list1,list2):
    return all(i in list2 for i in list1)

For your purpose, it seems it's more natural to use set.issubset here, which checks if list1 is a subset of list2:

def in_list(list1,list2):    
    return set(list1).issubset(list2)
  • Related