a = "3"
b = ["3"]
def func():
return a in b
The above function returns “TRUE”
But if I have my code as follows:
a="1,2,3,4" b = ["3"]
How do I check the elements of a one by one with b, i.e, “1”==[“3”] or “2”==[“3”], and so on, and return “TRUE” when “3”==[“3”]
Advertisement
Answer
Try this
a = "1,2,3,4"
b = ["3"]
def func(a, b):
return any(e in b for e in a.split(','))
print(func(a, b))
Output
True
- Use
split(',')for converting typestrtolist. - Code inside the
any()functione in b for e in a.split(',')returns a boolean list ofTrueandFalsebased on condition - Here
evalues are1,2,3,4; for each, check if elementeis in listb. - Use the
any()function; it returnsTrueif one of the conditions is true in the list.