Python For Loop Tutorial with Examples – POFTUT

Python For Loop Tutorial with Examples

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 specified list or array.

For Loop Python Syntax

The syntax for python for loop is like below.

Simple and Basic For Loop

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

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

Simple For Loop

Using Range

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. Range function gives the ability to define the start and end numbers.

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

Using Range

Using Range

Set Start an End

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.

LEARN MORE  In Python Operator Usage Tutorial with Examples

Set Start an End

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

Set Increment Count

Set Increment Count

Less Memory Usage With Xrange

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.

Less Memory Usage With Xrange

Less Memory Usage With Xrange

Iterate Over 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.

Iterate Over List

Iterate Over List

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)