0

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

  • 2
    You are returning after the first iteration of the loop. You need to loop through all the elements in `list1` to answer this question. You only want to return `False` inside the loop if the element is not in `list2`. After you get through the loop without returning false, only then can you return True. – Mark Feb 16 '22 at 21:58
  • The inner loop returns True if the _very first_ item in list1 is present in list2. Instead, the second loop should return True only after it has verified that _all_ the items in list1 are in list2. – John Gordon Feb 16 '22 at 22:01
  • Does this answer your question? [How to check if all items in a list are there in another list?](https://stackoverflow.com/questions/15147751/how-to-check-if-all-items-in-a-list-are-there-in-another-list) – Pranav Hosangadi Feb 16 '22 at 22:06

2 Answers2

2
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)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
1

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

ViaTech
  • 2,143
  • 1
  • 16
  • 51