How to keep track of whether all strings in a list have a specific string present in them?
<p>I have a list of strings within which I need to search for a specific sub-string and return a result only when the sub-string is present in every string that is in the list. My first idea was to create a list of boolean values that correspond with whether the sub-string is present in each larger string in my list, and then write another loop to check whether this list of booleans is True at every index. Does anybody have any suggestions for a more elegant and efficient method?</p>

<p>Thank you kindly!</p>

<p>I would use the built-in <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all</code></a> function along with <a href="https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions" rel="nofollow">generator expression</a> to avoid creating a throw-away intermediate list. Since the code can be expressed as one line, I'd also define it using a <a href="https://docs.python.org/3/reference/expressions.html#lambda" rel="nofollow"><code>lambda</code> expression</a> instead of the usual <code>def function()</code>:</p>

<pre><code># define function via lambda
in_all = lambda strings, specific: all(specific in strng for strng in strings)
in_all.__doc__ = """ Check whether all strings in list contain specified string. """

l1 = ["day", "lay", "may"]
l2 = ["day", "lay", "may", "not"]

print(in_all(l1, "ay"))  # -&gt; True (all had specific string)
print(in_all(l2, "ay"))  # -&gt; False (at least one didn't have
                         #           the specific string)
</code></pre>

python list boolean