Using return to Short-Circuit Your Loops
Now you’ll see how
return statements can speed up the execution of functions which use loops. When a Python function encounters a
return statement inside a loop, it immediately ends execution of the loop and the function and returns to where the function was called.
00:37 You always find your keys in the last place you look—if you don’t keep looking for them after you found them. We don’t need to process the rest of the collection, which improves the execution time of the function.
As per usual, we’ll process it one element at a time using a
for loop, calling each element
item. If at any iteration, that specific item has a truthy value, we can go ahead and return
True. If we know that there’s one in that collection, the return value for this function should be
If we completely process the collection and complete the execution of the
for loop, then there must not have been any element in the collection with a truthy value, so in that case, we’ll return
False to indicate that there weren’t any.
03:56 Otherwise, the function will return during the first iteration, which is probably not what you want. The remaining code will never be executed. That remaining code is an example of what we call dead code, and we’ll look at that in the next lesson.
Become a Member to join the conversation.