Control Flow (for)

The for loop

The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence (like a list or a string).

Example:

for i in range(1, 5):
    print(i)
else:
    print('The for loop is over')

Output:


1
2
3
4
The for loop is over

How It Works

In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in range function.

What we do here is supply it two numbers and range returns a sequence of numbers starting from the first number and up to the second number. For example, range(1,5) gives the sequence [1, 2, 3, 4]. By default, range takes a step count of 1. If we supply a third number to range, then that becomes the step count. For example, range(1,5,2) gives [1,3]. Remember that the range extends up to the second number i.e. it does not include the second number.

Note that range() generates only one number at a time, if you want the full list of numbers, call list() on the range(), for example, list(range(5)) will result in [0, 1, 2, 3, 4]. Lists are explained in the data structures chapter.

The for loop then iterates over this range - for i in range(1,5) is equivalent to for i in [1, 2, 3, 4] which is like assigning each number (or object) in the sequence to i, one at a time, and then executing the block of statements for each value of i. In this case, we just print the value in the block of statements.

Remember that the else part is optional. When included, it is always executed once after the for loop is over unless a break statement is encountered.

Remember that the for..in loop works for any sequence. Here, we have a list of numbers generated by the built-in range function, but in general we can use any kind of sequence of any kind of objects! We will explore this idea in detail in later chapters.

Note for C/C++/Java/C# Programmers

The Python for loop is radically different from the C/C++ for loop. C# programmers will note that the for loop in Python is similar to the foreach loop in C#. Java programmers will note that the same is similar to for (int i : IntArray) in Java 1.5.

In C/C++, if you want to write for (int i = 0; i < 5; i++), then in Python you write just for i in range(0,5). As you can see, the for loop is simpler, more expressive and less error prone in Python.

Summary

We have seen how to use the three control flow statements - if, while and for statements. These are some of the most commonly used parts of Python and hence, becoming comfortable with them is essential.