Python For Loop Tutorial with Examples

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-for-loop-tutorial-with-examples/
PINTEREST
PINTEREST
INSTAGRAM

Python programming language provides loops with for statement. It is similar to the most of the main stream programming languages like C, C++, Java or C# . We will look to the for loop Python examples.

For Loop Python Syntax

Syntax for python for loop is like below.

var is the variable which holds value for each step in loop.

arr is the list or array enumerated.

Simple and Basic For Loop

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

We loop over list which is consist of characters. We can directly run python script like below. Other way is to make 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 is not exists in python. But naturally it exists with range function. Range function gives the ability to define 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 start and end numbers. We can set start and end numbers like below in range  function too.

LEARN MORE  How To Download, Install and Use Python Idle Editor?

Set Start an End

Set Start an End

Set Increment Count

We can change 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 create 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 allready

Iterate Over List

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

Iterate Over List

Iterate Over List

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)