james jake
james jake

Reputation: 39

How can I check if one list is a subset of the another?

Here is the current code I have:

a = input('Enter words: ') 
b, c = a.split()
q = []
z = [] 

for i in b: 
    q.append(i)
for j in c: 
    z.append(j)

for letters in q: 
    if letters in z: 
        print('yes')

It will output 'yes' if the letter in q is also in z.

Is there someway to check if all instances of characters in one list are in another. Like:

for letters in q: 
    if all letters in z: #all
        print('yes')

Upvotes: 4

Views: 7241

Answers (2)

Cory Madden
Cory Madden

Reputation: 5193

lst1 = [1, 2, 3]
lst2 = [3, 4, 5]

set(lst1).issubset(lst2)
# False
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
set(lst1).issubset(lst2)
# True

Upvotes: 5

user94559
user94559

Reputation: 60143

I believe this is what you want:

if all(letter in z for letter in q):
    print('yes')

Simplified full working code:

q, z = input('Enter words: ').split()

if all(letter in z for letter in q):
    print('yes')

Sample runs:

$ python test.py
Enter words: cat tack
yes
$ python test.py
Enter words: cat bat

Upvotes: 1

Related Questions