The for..in statement is another looping statement where the number of times that the loop is executed is known (one way or another). The for statement is used to iterate over the elements of a sequence i.e. go through each item of a sequence. We will see more about sequences in detail in later chapters. What you need to know right now is that a sequence is just an ordered collection of items.
Example 6.4. Using the for statement
#!/usr/bin/python # Filename : for.py for i in range(1, 5): print i else: print 'The for loop is over.'
In this program, we are printing a sequence of numbers. We get 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) returns 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) returns [1, 3]. Remember, that the range extends up to the second number i.e. it does not include the second number.
The for loop then iterates over this range i.e. for i in range(1, 5) is equivalent to for i in [1, 2, 3, 4] which is like assigning each number in the sequence to i one at a time and executing the block of statements for each value of i. In this case, we print the value of i.
Remember that the else part is optional. When included, it is always executed once after the for loop is over.
Remember that the for..in loop works for any sequence. Here we have used a list generated by the built-in range function but in general, we can use any list, tuple or string. We will explore this in detail in later chapters.
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 write for (int i = 0; i < 5; i++), then in Python, you write for i in range(0, 5). As you can see, the for loop is simpler, more expressive and less error prone in Python.