For Loops


A loop takes a few lines of code, and runs them again and again. Most algorithms have a lines of code that need to be run thousands or millions of times, and loops are the way to do this.

For Loop - aka Foreach

The "for" loop is probably the single most useful type of loop. The for-loop, aka "foreach" loop, looks at each element in a collection once. The collection can be any type of collection-like data structure, but the examples below use a list.

Here is a for-loop example that prints a few numbers:

>>> for num in [2, 4, 6, 8]:
        print(num)
2
4
6
8

Loop Syntax: the loop begins with the keyword for followed by a variable name to use in the loop, e.g. num in this example. Then the keyword in and a collection of elements for the loop, e.g. the list [2, 4, 6, 8]. Finally there is colon : followed by the indented "body" lines controlled by the loop.

Loop Operation: the loop runs the body lines again and again, once for each element in the collection. Each run of the body is called an "iteration" of the loop. For the first iteration, the variable is set to the first element, and the body lines run (in this case, essentially num = 2. For the second iteration, num = 4 and so on, once for each element.

The main story of the for loop is that if we have a collection of numbers or strings or pixels, the for-loop is an easy way to write code that looks at each value once. Now we'll look at a few features and slightly subtle features of the loop.

Loops with range() Function

The python range() function creates a collection of numbers on the fly, like [0, 1, 2, 3, 4] This is very useful, since the numbers can be used to index into collections such as string. The range() function can be called in a few different ways.

range(n) - 1 Parameter Form

The most common form is range(n), for integer n, which returns a numeric series starting with 0 and extending up to but not including n, e.g. range(6) returns 0, 1, 2, 3, 4, 5.

>>> for i in range(6):
...   print(i)
... 
0
1
2
3
4
5

Loop Controls The Variable, Not You

Usually variables only change when we see an assignment with an equal sign =

The for-loop is strange, since for each iteration, the loop behind the scenes is setting the variable to point to the next value. Mostly this is very convenient, but it does mean that setting the variable to something at the end of the loop has basically no effect...

for num in [2, 4, 6, 8]:
    print(num)
    num = 100    # No effect on output,
                 # the loop resets num on each iteration