Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: One line for loop condition

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.

like image 741
Neil Graham Avatar asked Oct 27 '25 17:10

Neil Graham


1 Answers

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):
    ...
like image 137
Patrick Haugh Avatar answered Oct 29 '25 06:10

Patrick Haugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!