1

I would like to determine whether a list of strings can be found within another list of strings in python.

For example:

list1 = ['iguana','cat','spider','monkey','dog']
list2 = ['cat','dog']

result = False

for i in list1:
    for j in list2:
        if list1[i] == list2[j]
            result = True

print(result)

and the result is true, but this seems to cause problems on larger lists

Is there any way to search through the first list more efficiently with cleaner code?

4
  • 5
    Convert one to a set then use .issubset/.issuperset (depends on which one you converted) Commented May 18, 2021 at 21:42
  • I am confused, I am not familiar with subsets how do I do that? Commented May 18, 2021 at 21:43
  • You could try to use "set()" to check if there's intersection. Commented May 18, 2021 at 21:46
  • Thank you @DeepSpace I figured it out and it works Commented May 18, 2021 at 21:50

3 Answers 3

2

Your question was specifically about lists. I am presuming you are trying to ascertain if all elements in list2 are in list1. If so, then we're talking about sets, and then this would be a solution:

set1 = {"iguana", "cat", "spider", "monkey", "dog"}
set2 = {"cat", "dog"}
print(set2.issubset(set1))
Sign up to request clarification or add additional context in comments.

Comments

1

There is structure called set. It has very efficient functions checking if element presents in set or not. Also it has functions checking if another set is a subset of it. For example you have two lists.

list1 = ['iguana','cat','spider','monkey','dog']
list2 = ['cat','dog']

You can create two sets from them, and check if all elements of list2 presents in list1 (if this is what you want) like this.

set1 = set(list1)
set2 = set(list2)
answer = set2.issubset(set1)

Comments

0

You can give this a shot using list comprehension

list1 = ['iguana','cat','spider','monkey','dog']
list2 = ['cat','dog']

if [animal for animal in list2 if animal in list1] == list2:
    print(True)
else:
    print(False)

or you can use .issubset. But it seems others have suggested that already.

2 Comments

this solution is O(n^2) and set solution is O(n)
ok... Thank you for providing this information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.