How does infinite loop works?

Hello. I got this example from the infinite loop lesson.

In my_favorite_numbers variable, there are five numbers but how does this cause an infinite loop?

Thank you for your help.

Because it extends the list such that the end is never reached.

>>> s = [4, 8, 15, 16, 42]
>>> for n in s:
	s.append(1)
	if len(s) > 10: break


>>> print (s)
[4, 8, 15, 16, 42, 1, 1, 1, 1, 1, 1]
>>> 

The only thing to save us is the breaking condition, without which Python would have eventually run out of memory.

Bottom line, treat this exercise and the lesson seriously. We need to be very mindful of their termination when writing loops.

2 Likes