Python for Loop

Summary: in this tutorial, you will learn how to use the Python for loop statement to iterate over elements of a list, a tuple or a string.

Introduction to Python for loop statement

A for loop in Python is not similar to other languages such as C or Pascal which test a variable and increase it in each iteration. In Python, a for loop iterates over the items or any sequence in order that they are in the sequence. This means you can use the for loop to loop over a list, a tuple or a string which is quite flexible.

The syntax of the for loop is as follows:

The code-block will be executed once for each item in the sequence. The item variable is set to the element in the sequence.

Let’s take a look at an example of using for loop statement to print out a square number of each number in a list.

for loop with range function

The range function in Python creates a sequence which can be useful when combining with the for loop statement to loop over a sequence with explicit indices. The range function is as follows:

  • The arguments start, stop and step must be plain integers.
  • The default value of step parameter is 1. (if it is omitted)
  • The default value of start argument is 0. (if it is omitted)
  • The range function returns a list of plain integers [start, start + step, start + 2 * step, …].
  • If step is positive integer, the last element is largest which is start + i * step less than stop;
  • if step is negative integer, the last element is the smallest which is start + i * step greater than stop.
  • The step parameter must not be zero otherwise a ValueError  exception will be raised.

Here is the demonstration of the range() function:

Now we can use the range() function with the loop to iterate over each element of the list by indices.

for loop with else clause

The else clause, which is an optional part, comes together with the for loop statement. Here is the syntax of for loop with else clause:

The else-code-block is executed when the loop terminates through exhaustion of the list.

Here is an example of for loop with else clause to find a prime numbers.

In this tutorial, we have introduced you to Python for loop statement to iterate over elements of a list, a tuple or a string.

  • Was this tutorial helpful ?
  • YesNo