>A Byte of Python

The for loop

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.

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.