We’ve iterated through lists that have a discrete beginning and end. However, let’s consider this example:
my_favorite_numbers = [4, 8, 15, 16, 42] for number in my_favorite_numbers: my_favorite_numbers.append(1)
What happens here? Every time we enter the loop, we add a
1 to the end of the list that we are iterating through. As a result, we never make it to the end of the list! It keeps growing!
A loop that never terminates is called an infinite loop. These are very dangerous for your code!
A program that hits an infinite loop often becomes completely unusable. The best course of action is to never write an infinite loop.
Note: If you accidentally stumble into an infinite loop while developing on your own machine, you can end the loop by using control + c to terminate the program. If you’re writing code in our online editor, you’ll need to refresh the page to get out of an infinite loop!
Suppose we have two lists of students,
students_period_B. We want to combine all students into
Write a for loop that goes through each
students_period_A and adds it to the end of
Inside the for loop, after appending
Let’s suppose you made a typo in the body of your for loop. Oh no! We will go through a few steps to see what happens when you end up with an infinite loop and how you fix it:
Inside the for loop, change the object of the append statement from
Run this code. What do you notice happens? Over the run button, notice the loading circle is continuing without anything happening. This is an infinite loop! To end this program we must refresh the page. (Note: The reason this loop is infinite is that we’re adding each student in
students_period_Awhich would create a never-ending list of all the student names.)
After refreshing your page, you should see that the run button is back. Now get rid of the change we made that caused an infinite loop by changing the object of the append statement back to
Run your code again. This time your loop should not be infinite, and it should run to completion.
Great job! We have now seen what happens when you run an infinite loop and how we can fix them! Revel in the safety of your code, and how it doesn’t crash your browser. Run it one final time to make sure it is working as expected.