16th Dec 2021 8 minutes read How to End Loops in Python Luke Hande python learn python Knowing how to exit from a loop properly is an important skill. Read on to find out the tools you need to control your loops. In this article, we'll show you some different ways to terminate a loop in Python. This may seem a little trivial at first, but there are some important concepts to understand about control statements. We'll also introduce some lesser-known ways to end loops in Python to give you tools for greater control over how your programs are executed. If you're a beginner to Python, we recommend starting with this article to learn some of the terms we use. Or feel free to check out this course, which is perfect for beginners since it assumes no prior knowledge of programming or any IT experience. Iterating With for Loops The entry point here is using a for loop to perform iterations. The for loop is one of the most important basic concepts in Python. You'll come across them in many contexts, and understanding how they work is an important first step. For people new to Python, this article on for loops is a good place to start. Basically, a for loop is a way to iterate over a collection of data. The data may be numerical, for example, a float-point number or an integer, or even text data, and may be stored in different structures including lists, tuples, sets, and dictionaries. For more in-depth material on these data structures, take a look at this course. It Ain't Over Till It's Over This linguistic tautology has been the mantra of many an underdog in a competition. It is also the first stop in our discussion on how to end a loop in Python. We can define an iterable to loop over with any of the data structures mentioned above. Alternatively, we can also use the built-in range(), which returns an immutable sequence. For some practical exercises using built-in functions, check out this course. range() accepts 3 integer arguments: start (optional, default 0), stop (required), and step (optional, default 1). It returns a sequence with a pre-defined number of elements. We can loop over the elements in a sequence as follows: >>> for i in range(-2, 11, 3): >>> print(i) -2 1 4 7 10 There are a few interesting things about this example. First, the arguments can be negative. You can even specify a negative step to count backward. Try it out for yourself. Second, reaching the exact stop value is not required. In the example above, we progress through the sequence starting at -2, taking steps of 3, and then we stop at 10. This is before the defined stop value of 11, but an additional step of 3 takes us beyond the stop value. This is the most obvious way to end a loop in Python – after a pre-defined number of iterations. If you want to iterate over some data, there is an alternative to the for loop that uses built-in functions iter() and next(). The first defines an iterator from an iterable, and the latter returns the next element of the iterator. The loop, or the iteration, is finished once we return the last element from the iterator. Calling next() after that raises the StopIteration exception. You can iterate only once with these functions because the iterable isn't stored in memory, but this method is much more efficient when dealing with large amounts of data. If you want to see some concrete examples of how to apply these two functions for efficient looping, check out this article. Loop Control Statements break The break statement is the first of three loop control statements in Python. It is used in conjunction with conditional statements (if-elif-else) to terminate the loop early if some condition is met. Specifically, the break statement provides a way to exit the loop entirely before the iteration is over. The following example demonstrates this behavior: >>> for i in range(5): >>> if i == 3: >>> break >>> print(i) >>> print('Finished') 0 1 2 Finished We use range() by specifying only the required stop argument. In this case, the start and the step arguments take their default values of 0 and 1, respectively. Simply looping through range(5) would print the values 0 – 4. Instead, we check if the element is equal to 3, and if so, the break statement stops the loop completely. The final line, print('Finished') is outside the loop, and therefore still gets executed after the loop is broken. continue Contrast this with the continue statement, as shown below: >>> for i in range(5): >>> if i==3: >>> continue >>> print(i) >>> print('Finished') 0 1 2 4 Finished Once the condition in the second line evaluates to True, the continue statement skips over the print statement inside the loop. It then continues the loop at the next element. The loop ends when the last element is reached. This is handy if you want your loop to complete but want to skip over just some of the elements. And as seen above, any code below and outside the loop is still executed. pass The third loop control statement is pass. Strictly speaking, this isn't a way to exit a loop in Python. However, it's worth mentioning because it pops up often in contexts similar to the other control statements. Try out the above example with a pass statement instead of continue, and you'll notice all elements defined by range() are printed to the screen. The pass statement serves as a placeholder for code you may want to add later in its place. Proceed to the Emergency Exit in Python The features we have seen so far demonstrate how to exit a loop in Python. If you want to exit a program completely before you reach the end, the sys module provides that functionality with the exit() function. Calling this function raises a SystemExit exception and terminates the whole program. sys.exit() accepts one optional argument. It may be either an integer or a string, which may be used to print an error message to the screen. Let's take a look at an example: >>> import sys >>> for i in range(5): >>> if i == 3: >>> sys.exit('Error message') >>> print(i) >>> print('Finished') 0 1 2 SystemExit: Error message In this context, sys.exit() behaves similarly to break in the earlier example, but also raises an exception. As a result, the final print statement outside the for loop is not executed in this example. The whole program is simply terminated. Looping Over Lists A common operation to perform in a loop is modifying a data structure such as a list. If you want to remove an element from a list during a loop, you may find yourself reaching for the del keyword, especially if you have a background in other programming languages like C++ or Java. This can be a handy tool since it can remove elements from data structures as well as delete local or global variables. But it can get a little tricky if you're changing a list while looping over it. Consider the following example, where we want to remove all odd numbers from a list of numbers: >>> numbers = [1, 1, 2, 3, 4, 5, 6] >>> for i in range(len(numbers)): ... if numbers[i] % 2 != 0: ... del numbers[i] Executing this code will produce IndexError: list index out of range. We have defined our loop to execute for 7 iterations (the length of the list). Since we defined this with range(), it is immutable. During the loop, we start to remove elements from the list, which changes its length. It now has fewer elements than the sequence over which we want to iterate. Moreover, if you take a moment to consider the example, you see the second 1 won't be deleted because it slips to the 0 position whereas the loop goes to the position with the index 1. To remedy all of this, we can use a clever trick to iterate over the elements in reverse order, using the built-in function reversed(): >>> numbers = [1, 1, 2, 3, 4, 5, 6] >>> for i in reversed(range(len(numbers))): ... if numbers[i] % 2 != 0: ... del numbers[i] The reversed() function returns an iterator, which we mentioned earlier in the article. Alternatively, you can use range() to count backward during the iteration as we noted earlier. These methods remove elements from the end of the list, ensuring the current list index is never larger than the length of the list. Or even better, we can use the most Pythonic approach, a list comprehension, which can be implemented as follows: >>> numbers = [1, 1, 2, 3, 4, 5, 6] >>> numbers = [num for num in numbers if num % 2 == 0] For those of you who haven't seen this kind of magic before, it's equivalent to defining a list, using a for loop, testing a condition, and appending to a list. Normally, this would take 4 lines. But with a list comprehension, we achieve this in just one! Get More Control and End Loops in Python This discussion has focused on how to exit a loop in Python – specifically, how to exit a for loop in Python. We'd like to encourage you to take the next step and apply what you've learned here. Like we've said before, start by taking small steps and work your way up to more complex examples. Try to experiment with while loops. You may discover there's a more fundamental way to exit a while loop that doesn't apply to for loops – when the condition defined by the while statement evaluates to False. As another extension, test out what happens when you use nested for loops with control statements. You'll find you can modify one loop, while the other continues executing normally. With a little bit of practice, you'll master controlling how to end a loop in Python. Tags: python learn python