Iteration is about running blocks of code repeatedly.
There are two redundant approaches to achieving that.
First, we combine functions that call themselves with conditional statements. This concept is known as recursion and suffices to control the flow of execution in every way we desire. For a beginner, this approach of backward reasoning might not be intuitive, but it turns out to be a handy tool to have in one's toolbox.
Second, the while
and for
statements are alternative and potentially more intuitive ways to express iteration as they correspond to a forward reasoning. The for
statement is syntactic sugar that allows rewriting common occurrences of the while
statement concisely. Python provides the break
and continue
statements as well as an optional else
-clause that make working with the for
and while
statements even more convenient.
Iterables are any concrete data types that support being looped over, for example, with the for
statement. The idea behind iterables is an abstract concept that may or may not be implemented by any given concrete data type. For example, both list
and range
objects can be looped over. The list
type is also a container as any given list
objects "contains" references to other objects in memory. On the contrary, the range
type does not reference any other object but instead creates new int
objects "on the fly" (i.e., when being looped over).