Skip to content
Advertisement

How to get items that are true for ANY() method in Python

Say:

x = 'A/B'
any(signs in x for signs in ['/' , '+', '-'])

How to get the signs it found true in the iteration? Here’s a way

for sign in ['/' , '+', '-']:
    if sign in x:
        print(sign)

Is there a better one liner way of doing it? (Without the for loop maybe)

Advertisement

Answer

With the few modifications to the any expression, you can get whether each of the signs is in the expression, which signs are in the expression, or just the first such sign:

>>> any(sign in x for sign in ['/' , '+', '-'])
True
>>> [sign in x for sign in ['/' , '+', '-']]
[True, False, False]
>>> [sign for sign in ['/' , '+', '-'] if sign in x]
['/']
>>> next((sign for sign in ['/' , '+', '-'] if sign in x), None)
'/'

(In the last one, None is the default in case no such element exists.)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement