8

I'd like to find if a list of substrings is contained in a list. For example, I have:

    string_list = ['item1', 'item2', 'subject3', 'subject4']

and list of substrings

    substrings = ['item', 'subject']

I'd like to find if 'item' or 'subject' are included in any item of string_list. Individually, I would do something like:

    any('item' in x for x in string_list)

This works for one substring but I would like to find a pretty way of searching for both strings in the list of substrings.

3
  • 1
    You could nest anys, or write a more complex generator expression to create the cross product, or use itertools.product to do it for you. Commented Aug 28, 2017 at 20:18
  • What is your expected result? Do you want matches where the string_list starts with the substring item, or exact matches? Commented Aug 28, 2017 at 20:25
  • I'd just like a true or false of whether or not the list of strings contains any of the the strings in the substring list. Commented Aug 28, 2017 at 20:28

3 Answers 3

7
any(y in x for x in string_list for y in substrings)
Sign up to request clarification or add additional context in comments.

Comments

2

Since the substrings are actually at the start, you can use str.startswith which can take a tuple of prefixes:

any(x.startswith(('item', 'subject')) for x in string_list)

Comments

1

You can try this:

string_list = ['item1', 'item2', 'subject3', 'subject4']

substrings = ['item', 'subject']

any(any(b in i for b in substrings) for i in string_list)

Output:

True

Comments

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.