Search code examples
pythonfor-loopreturn

What is the right place to put "return"?


I am a new bird following udacity to learn some python. Got really confused about where to put the return to end a loop. I understand that the code provided in the answer will work. But I don't understand why my own code wouldn't. I would really appreciate some help! Thank you very much!

The quiz is: Define a procedure, add_to_index, that takes 3 inputs:

  • an index: [[,[,...]],...]
  • a keyword: String
  • a url: String

    If the keyword is already in the index, add the url to the list of urls associated with that keyword.

    If the keyword is not in the index, add an entry to the index: [keyword,[url]]

my code is:

index = []
def add_to_index(index,keyword,url):
    for element in index:
        if element[0] == keyword:
            element[1].append(url)
        else:
            index.append([keyword,[url]])
        return index

and the answer given is:

index = []
def add_to_index(index,keyword,url):
    for element in index:
        if element[0] == keyword:
            element[1].append(url)
            return
    index.append([keyword,[url]])

why does the index.append([keyword,[url]]) have to be out of the loop? I thought after each element in the index was went through, the loop will terminate itself. Is it true?


Solution

  • Please note that a loop, by its very definition, loops through all the iteratable items.

    In the quiz mentioned above, a new [keword,[url]] item should be appended if it wasn't there before. You can only tell that after you check the entire data structure, therefore after the loop.

    Note that the interpreter will run the "return" statement only if the "keyword" was found in any of the iterations of the loop. Its purpose is simply to stop the execution of the function once the desired functionality has been achieved. Hence a return that returns "nothing" (more precisely None).