Looping through a predefined list

  1. Define a list containing numbers:

    >>> primes = [2, 3, 5, 7]

  2. Specify a loop to iterate over the list and display each member:

    >>> for prime in primes:

            print prime

    2

    3

    5

    7

    Note: Line indentation is very important. It specifies which statements are part of a block. In the example above, the print statement must be indented to be part of the for loop block. And if you want to include further statements in the loop block, they need to be given the exact same level of indentation. Without the correct level of indentation, statements will not be included in blocks in your code.

See also

Starting the Python shell

Printing hello world

Using basic variables

Creating an array and a dictionary and printing values

Looping using the xrange function