In the example below, I am testing whether any characters in the variable 'characters' are found in the string 'hello'.
characters = ['a','b','c','d']
if True in [c in 'hello' for c in characters]: print('true')
else: print('false')
The one line for loop creates a list of boolean values. I'm wondering if there's any way to not create the list and rather pass the whole condition once one of the conditions in the loop has passed.
You can use any with a generator expression. This will take values from the generator one at a time until the generator is exhausted or one of the values is truthy.
The generator expression will only calculate values as needed, instead of all at once like the list comprehension.
if any(c in 'hello' for c in characters):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With