Search
More Flow Control: For and While Loops

Looping structures, i.e. for and while loops, are another method of flow control in Python programming. They can be used to perform structured and/or repeated tasks that occur numerous times in a compact way.

For loops

For loops are a looping structure that allows for iteration over a fixed number of items. The items can simply be monotonically increasing integers, in which case the loop simply cycles a fixed number of times. Additionally, the items can by items from a Python list, tuple, or dict.

For demonstration purposes, let's start with a Python list with mixed data types.

alist = [1, 2.0, 'hello']

Now we can write a for loop that iterates over each item in the list one at a time and prints the item to the screen.

In this loop item becomes a variable internal to the loop that each entry in alist gets assigned to one-by-one as the program cycles through the body of the loop until the end of alist has been reached.

for item in alist:
    print(item)
1
2.0
hello

The loop above is exactly equivalent to this code

item = alist[0]
print(item)
item = alist[1]
print(item)
item = alist[2]
print(item)
1
2.0
hello

The code above is said to be the unrolling of the loop. Of course, if alist had many items in it, we would not want to type all the lines of code required to perform the operation without the loop.

Just like Python functions and if statements, loops use whitespace indentation to indicate the body of the loop. What is in the body gets executed every cycle through the loop, any valid Python code can be placed in the body. For example, a simple computation

The range() function provides a quick way to generate a monotonically increasing set of integers for iteration. If only one argument is given, i.e. range(5), then the resulting integers start at 0 and increment by 1 up to, but not including, the number given as the argument. Additional reading on the range() function can be found here.

for i in range(5):
    print(i ** 2)
0
1
4
9
16

Tuples can be iterated over in a for loop just like lists.

atuple = (1, 3, 5)

for item in atuple:
    print(item)
1
3
5

Dictionaries can also be iterated over, in this case, the use of the items() function allows for both the keywords and the values to be unpacked and assigned each to variables local to the loop.

If only dictionary keywords where desired for iteration in the loop, the keys() function could be used in place of items(). Likewise values() can be used if only the values are desired.

adict = {"name1": "Romeo", "name2": "Juliet"}

for keyword, value in adict.items():
    print('"{}" is {}'.format(keyword, value))
"name1" is Romeo
"name2" is Juliet

Often times we would like to store the results of computations in a list at the loop executes. One way to do this is using the append() function defined for Python lists. Here we start with an empty list and append the square of the integer range of numbers from 0 to 9 each cycle through the loop.

alist = []

for item in range(10):
    alist.append(item ** 2)
    
print(alist)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

List comprehensions

There is another type of for loop structure that can be used in Python when it is desired to store the output of computations from a loop in a list. These are called list comprehensions. The syntax is a little strange, but they are much faster at producing lists as an output of the loop. An example of a list comprehension that produces the same result as the for loop above is

In a list comprehension, the body of the loop goes before the for keyword. More on list comprehensions can be found here.

alist = [item ** 2 for item in range(10)]
print(alist)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Enumerate

Occasionally, in addition to iterating over the actual items in a list/tuple, the integer index corresponding to the location in the data structure is also desired. This can be returned with the enumerate() function. For example,

atuple = ("a", "tuple", "of", "strings")

for count, item in enumerate(atuple):
    print('"{}" -- has the index {}'.format(item, count))
"a" -- has the index 0
"tuple" -- has the index 1
"of" -- has the index 2
"strings" -- has the index 3

While loops

While loops continuously execute the body of the loop so long as some conditional statement is evaluating to True. The conditional statement appears to the right of the while keyword. In the example below, we use a very simple conditional statement, but any valid conditional expression in Python, including and and or clauses can be used.

Here the conditional statement is i < 5 which of course is True with the given initial value of i=0. So the body of the loop executes, each time incrementing i by 1, until i = 5 which causes the conditional statement to evaluate to False and the loop exits.

i = 0

while i < 5:
    
    print(i)
    
    i += 1
0
1
2
3
4

If the conditional statement in a while loop never evaluates to False, the loop will execute ad infinitum. If new variables are being assigned in the body of the loop or the results of computations are stored, the infinite cycling can cause the computer's memory to fill and possibly lead to a crash of the program and/or computer. It's often desirable to have a set number of maximum iterations that if reached will guarantee the loop will exit. In this case, the functionality of a while loop can be replicated with the combination of a for loop and an if statement with a break keyword. For example, the while loop structure above is replicated in the following code, but with the guard that the maximum number of iterations cannot exceed 10.

for i in range(10):
    
    if i > 4:
        break
    
    print(i)
0
1
2
3
4

Further reading

Further reading on Python flow control with loops can be found in the Python documentation.