Search code examples
pythonlistfunctionnonetype

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

  • 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