Python Forum

Full Version: How to check if a list is in another list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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
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
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'}
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.