7.1. Introduction: Iteration¶
A basic building block of all programs is to be able to repeat some code over and over again. Whether it is updating the bank balances of millions of customers each night, or sending email messages to thousands of people programming involves instructing the computer to do many repetitive actions. In computing, we refer to this repetitive execution as iteration. In this section, we will explore some mechanisms for basic iteration.
With collections (lists and strings), a lot of computations involve processing one item at a time. For strings, this means that we would like to process one character at a time. Often we start at the beginning, select each character in turn, do something to it, and continue until the end. For example, we could take each character and substitute for the character 13 characters away in the alphabet to create a coded message.
This pattern of processing is called a traversal, or iteration over the characters. Similarly, we can process each of the items in a list, one at a time, iterating over the items in the list. This has applications in every piece of software you can imagine:
Displaying a list of friends on SnapChat
Updating the position of every character on the screen of a video game
Displaying the locations that Doctors Without Borders operates in