Python Forum
How to check if a list is in another list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to check if a list is in another list (/thread-36106.html)



How to check if a list is in another list - finndude - Jan-17-2022

Hi All,

I have the below code:

list_1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

win_1 = ["1", "2", "3", "4"]

if win_1 in list_1:
    print("yes")
It doesn't print anything, how do I check if a list is in another list?


RE: How to check if a list is in another list - menator01 - Jan-17-2022

Not sure what you want but, this will print anything from win_1 that is in list_1
list_1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
win_1 = ["1", "2", "3", "4"]

for item in list_1:
    if item in win_1:
        print(item)
Output:
1 2 3 4



RE: How to check if a list is in another list - buran - Jan-17-2022

list_1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
win_1 = ["1", "2", "3", "4"]
win_2 = ['1', '12']

print(all(item in list_1 for item in win_1))
print(all(item in list_1 for item in win_2))
Output:
True False



RE: How to check if a list is in another list - perfringo - Jan-17-2022

Membership testing in a set is faster than membership testing in a list. However, converting list to set also costs some time. So it's up to specific conditions and terms what to prefer.

list_1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
win_1 = ["1", "2", "3", "4"]

print(set(win_1).issubset(list_1))              # are all win_1 elements in list_1
print(set(win_1).intersection(list_1))         # what elements of win_1 in list_1
Output:
True {'4', '3', '2', '1'}



RE: How to check if a list is in another list - bowlofred - Jan-17-2022

Looks like you're asking about a subsequence. You can check if a slice of a list matches your subsequence.

list_1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
 
win_1 = ["1", "2", "3", "4"]
 
if any(win_1 == list_1[x:x+len(win_1)] for x in range(len(list_1) - len(win_1) + 1)):
    print("yes")
List slicing and list comparison can take a while. So this can be expensive as the lists get long.