Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a list contains any one of multiple characters

Tags:

python

list

I'm new to Python. I want to check if the given list A contains any character among ('0', '2', '4', '6', '8') or not, where '0' <= A[i] <= '9'.
I can do this as:

if not ('0' in A or '2' in A or '4' in A or '6' in A or '8' in A):
    return False

but, is there any shorter way to do this? Thanks.

like image 503
GURU Shreyansh Avatar asked Mar 02 '23 12:03

GURU Shreyansh


2 Answers

You can use any with generator expression

A = [...]
chars = ('0', '2', '4', '6', '8')
return any(c in A for c in chars)
like image 161
Guy Avatar answered Mar 04 '23 01:03

Guy


You can try a for loop:

for i in '02468':
    if i not in A:
        return False

If you want True to be returned if all of the characters are found:

for i in '02468':
    if i not in A:
        return False
return True
like image 39
Ann Zen Avatar answered Mar 04 '23 02:03

Ann Zen