Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I check whether comma separated elements of a string are in the list or not?

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"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 string to list.
  • Code inside the any() function e in b for e in a.split(',') returns a list of True and False based on condition, Here e values are 1, 2, 3, 4 one by one and check if e is in b list.
  • Use the any() function, It returns True if one of the conditions is True in the list.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading