Checking if a list contains any one of multiple characters

Viewed 658

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.

4 Answers

You can use any with generator expression

A = [...]
chars = ('0', '2', '4', '6', '8')
return any(c in A for c in chars)

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

Maybe you could use the data structure Sets:

targets = ('0', '2', '4', '6', '8')
A = ('0', '0', '5', '9')

len(set.intersection(set(targets), set(A))) > 1

Where, in this case:

set.intersection(set(targets), set(A))
#=> {'0'}

You could do

A = ["1", "2", "3", "4", "5"]
B = ("0", "2", "4", "6", "8")

def contains(list_A, list_B):
    for char in list_B:
        if char in list_A:
            contains = True
    return contains

print(contains(A, B))

It goes through each character in list_B and checks if it is in list_A and if it is it sets the variable contains to True.

Then it returns this value

Related