Python programming language provides loops with for statement. It is similar to most of the mainstream programming languages like C, C++, Java, or C#. We will look to the for loop Python examples. for loop mainly used to iterate over a specified list or array.

For Loop Python Syntax

The syntax for python for loop is like below.

for var in arr: statement-1 statement-2 ...

Simple and Basic For Loop

Here is a simple for loop example which enumerates over a list

#!/usr/bin/python3 a=['p','o','f','t','u','t'] for var in a: print(var)

We loop over a list which is consist of characters. We can directly run the python script like below. Another way is to make the python script executable and then run.

Simple For Loop

Using Range For Iteration

In general popular programming languages gives the ability to specify start, step, and end definition for counting in for loop. At first, it may seem it does not exist in python. But naturally, it exists with range function. The range() function gives the ability to define the start and end numbers.

#!/usr/bin/python3 for var in range(5): print(var)

Here range function will start from 0 and count 5 numbers up to 4 with 1 by 1

Using Range

Set Start an End Items

In some cases, we also need to set the start and end numbers. We can set start and end numbers like below in range function too.

#!/usr/bin/python3 for var in range(5,12): print(var)

Set Start an End

Set Increment Count

We can change the stepping function and increment numbers with 2. For the range function, we will provide (0,6,2) 0 is the start number, 6 is end number and increment value is 2

#!/usr/bin/python3 for var in range(0,12,2): print(var)

Set Increment Count

Less Memory Usage With xrange() Function

To make loops more memory efficient xrange() function can be used. xrange() function is an enumerator and creates new instances if it is needed. Range function creates all range at the start. xrange can only be used with Python2 because the features of xrange is implemented in Python3 range already.

#!/usr/bin/python3 for var in xrange(1,6): print var

Less Memory Usage With Xrange

Iterate Over Given List

For loop can be used in all iterable types like a dictionary, list, etc. We can iterate over a list like below. Actually every list is an iterable struct in Python.

#!/usr/bin/python3 a=['p','o','f','t','u','t'] for var in a: print(var)