Python: One line for loop condition

Viewed 7543

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.

4 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):
    ...

Yes, you can use the built-in function any for that.

if any(c in 'hello' for c in characters): print('true')

You could use set's intersection to get the intersecting characters of both texts. If you got any, they were in it, if the intersect-set is empty, none were in it:

characters = set("abcd")  # create a set of the chars you look for
text = "hello"
charInText = characters & set(text) # any element in both sets? (intersection)
print ( 'true' if charInText != set() else 'false')  # intersection empty?

text = "apple"
charInText = characters & set(text) 
print ( 'true' if charInText != set() else 'false') 

Output:

false # abcd + hello true # abcd + apple

try this by declaring the list before.

characters = ['a','b','c','d']
    a = []
    if True in a = [c in 'hello' for c in characters]: print('true')
    else: print('false')
Related