This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: for loops

for or while?

face Josiah Wang

When should you use a for loop vs a while loop?

I say: use a for loop when you are iterating over a fixed collection.

As good programming practice, you should NOT modify the list while iterating over the list. For example, do not add elements to or delete elements from a list while iterating over the list. It is hard to read, and there may be unintended side-effects! It is better to treat the list as “read only” when inside the loop. Use a new list if you want to write new values to it.

Otherwise, consider a while loop. You have more control over the elements in the collection, for example allowing you to move anywhere you like without being restricted to a fixed sequence.