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

If String(s) in List, output the index of List and which String(s) was found

py_list = ['Big apple pie','Small blueberry Pie','Cold Cherry Pie','Hot keylime pie']

keywords = ['blueberry','keylime']

for text in py_list:
    if any(xs in text for xs in keywords):
        itemlist = (py_list.index(text))
        print(xs,"was found in index: ", itemlist " of py_list")

Traceback (most recent call last):
NameError: name ‘xs’ is not defined on line 7

How could I get output to be:

blueberry was found in index: 1 of py_list
keylime was found in index: 3 of py_list

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 :

Firstly, you’re misusing the any function. any() accepts an iterable and returns True when it finds that one of the items in the iterable is True or has a True boolean value.

Secondly, you’ll need to declare the variable in the for loop at a higher hierarchy for it to reach the statements within the if statement, like so.

py_list = ['Big apple pie', 'Small blueberry Pie', 'Cold Cherry Pie', 'Hot keylime pie']

keywords = ['blueberry', 'keylime']

for text in py_list:
    for xs in keywords:
        if xs in text:
            itemlist = (py_list.index(text))
            print(xs, "was found in index: ", itemlist, " of py_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