JavaScript
x
6
1
a = "3"
2
b = ["3"]
3
4
def func():
5
return a in b
6
The above function returns “TRUE”
But if I have my code as follows:
JavaScript
1
3
1
a="1,2,3,4"
2
b = ["3"]
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
JavaScript
1
9
1
a = "1,2,3,4"
2
b = ["3"]
3
4
def func(a, b):
5
return any(e in b for e in a.split(','))
6
7
8
print(func(a, b))
9
Output
JavaScript
1
2
1
True
2
- Use
split(',')
for converting typestr
tolist
. - Code inside the
any()
functione in b for e in a.split(',')
returns a boolean list ofTrue
andFalse
based on condition - Here
e
values are1
,2
,3
,4
; for each, check if elemente
is in listb
. - Use the
any()
function; it returnsTrue
if one of the conditions is true in the list.