Python For Loop

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-for-loop/
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 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.

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

Set Start an End

We can set start and end numbers like below.

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

LEARN MORE  How To Repair Ext2, Ex3, Ext4 File System In Linux?

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.

Iterate Over List

For loop can be used in all iterable types like dictionary, list etc. We can iterate over list like below

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

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)