Python For Loop Tutorial With Examples and Range/Xrange Functions – POFTUT

Python For Loop Tutorial With Examples and Range/Xrange Functions


For loop is used to iterate over given sequence. Sequence can be a list, dictionary or similar enumerable object for python programming language. For loop is a bit different from other languages like C, C++, Java … For loop in python mainly uses object to iterate but in other languages counting and statements are used mainly.

Syntax

Syntax of for loop is like below which consist of for keyword an item, in keyword and iterable object which ends with double point :

After the first line of for loop the loop body starts and which is expressed with indentation.

for item in iterable_object:
   print item

In the first step first value from iterable_object is assigned into item and the body of the for loop is executed. print item is for loop body. For loop body can be more than one line. For each step this operation will be done iteratively by assigning next value from iterable object.

Loop with For

Now we have simply looked syntax of for loop in previous part. But the best way to learn for loop is running examples. In this part we will run simple but useful example.

In this example we will provide a list which consist of numbers from 0 to 9 into a for loop and print this numbers to the screen.

mylist=[0,1,2,3,4,5,6,7,8,9]

for item in mylist:
   print(item)
Loop with For
Loop with For

Loop With Range

Previous part we have used a list which is already created explicitly to iterate. But the problem is how can we cope in a situation where we will iterate from 0 to 100.000 . Creating a list manually is just a joke. In this situations we can use range function which will create a list for given range. The most readable usage is providing start and end numbers to the range function.

LEARN MORE  Python JSON Encoder and Decoder Tutorial with Examples

In this example we will print numbers from 0 to 100 with range function in a for loop.

for item in range(0,100):
   print(item)
Loop With Range
Loop With Range

Set Range Steps

In previous part we started loop from 0 and incremented in each step one by one upto 100. Increasing one by one is not ideal for some situations. We can specify the increase value into the range function.

In this example we will increase the loop with 2 by providing third argument into range function like below.

for item in range(0,100,2):
   print(item)
Set Range Increase
Set Range Increase

Nested For Loop

Up to now we have used single for loop for iteration. But in real world situations we may need multiple for loops nested together. Matrixes are one of the most used are of nested loops where x and y coordinates are iterated in a nested manner. Nested loop is not different from normal loop we will just provide new for loop in the body block of the another for loop.

x=[1,2,3]
y=[1,2,3]

for a in x:
   for b in y:
      print(a,b)
Nested For Loop
Nested For Loop

Break For Loop

Starting a for loop will end after all elements are iterated. This is the most used scenario but there are some exceptions. In some situations we may want to break the loop if a specified condition is met. We can stop and exit from loop by using break keyword.

In this example we will look if the square root of the var and if it is above 20 we will stop and exit from for loop.

mylist=[3,2,1,5,4,2]

for var in mylist:
   if(var**2>20):
      break
   print(var)
Break For Loop
Break For Loop

Skip Current Step/Iteration

Another useful feature is skipping current into next step without running current step. We can use continue keyword to iterate next step. This will prevent executing for loop body part after continue keyword.

LEARN MORE  In Python Operator Usage Tutorial with Examples

We will use previous example but only skip next iteration if the var square root is bigger than 20 .

mylist=[3,2,1,5,4,2]

for var in mylist:
   if(var**2>20):
      continue
   print(var)
Skip Current Step
Skip Current Step

Loop/Iterate Dictionary

Another iterable type of python is dictionaries. We can iterate over a dictionary like a list and use both the key and value parts specifying as two items in a for loop.

We will extract both key and value pairs from dictionary named mydict by using items function and set them variables named key and value

mydict={'a':1,'b':2,'c':3}

for key,value in mydict.items():
   print(key,value)
Loop/Iterate Dictionary
Loop/Iterate Dictionary

For Else

Python provides decision making mechanisms with if-else keywords. For loops also provides else which can be used to detect break operation. As stated in break section break will finish for loop. If we need to run some code after finishing loop without break we can add else condition.

In this example we will print Loop finished if break is not fired.

mylist=[3,2,1,5,4,2]

for var in mylist:
   if(var**2>100):
      break
    print(var)
else:
   print("Loop finished")
For Else
For Else

Leave a Comment