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

Getting None instead of empty list

I want to get back [], but instead i get None.
When i put existing str as a keyword, for example: ‘casino’, i get a proper result: [0].

def word_search(doc_list, keyword):
    for i in doc_list:
            list = []
            words = i.split()
            for n in words:
                if keyword == n.rstrip('.,').lower():
                    list.append(doc_list.index(i))
                    return list
word_search(['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?'], 'ear')

>Solution :

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

You’ll need to be a bit more careful with your indents. When control falls off the end of the function without encountering that return list, you get an implicit return None.

def word_search(doc_list, keyword):
    list = []
    for i in doc_list:
        words = i.split()
        for n in words:
            if keyword == n.rstrip('.,').lower():
                list.append(doc_list.index(i))
    return list

might be a good first start, but we can do better with enumerate so you don’t need the index call (and you also don’t really want to use list as a variable name, since it shadows the built-in type for lists):

def word_search(doc_list, keyword):
    results = []
    for i, doc in enumerate(doc_list):
        words = doc.split()
        for n in words:
            if keyword == n.rstrip('.,').lower():
                results.append(i)
    return results 

We can still improve things a bit, if you’d only like each document index to appear once in the results:

def word_search(doc_list, keyword):
    results = []
    for i, doc in enumerate(doc_list):
        if any(keyword == word.rstrip('.,').lower() for word in doc.split()):
            results.append(i)
    return results 
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