Python For Loop how to use Examples

in this post, we are going to understand Python For Loop how to use Examples that include how to use for loop to iterate over a List, a tuple, a dictionary and for loop range(), for loop with else, for loop with continue statement.

What is the need of loops?


  • Loops in any programming language are used to execute the same set of statements n numbers of times.
  • Suppose we have to print the names of 100 employees instead of writing 100 print statements. We can run a loop that executes the same code statement 100 times.

How to use Python for loop


For Loop in Python is used to iterate over a sequence ( list, string, tuple), iterables(set, dictionary), numeric range sequence, and run some blocks of code till the size of the sequence, numeric range sequence, or iterable meets the condition set for this loop.

iteration: The action of looping over the sequence or iterable is known as iteration

Syntax of for loop in python

for variable in sequence
   ...code statement_1
    ...code statement_2
    ...code statement_N
  
  • Variable: In this syntax, the variable represents each element of sequence or iterable, the value of variable changes on each iteration it takes values of the next item.
  • Sequence :This represent sequence (list,string,tuple) or iterable(dictionary,set)

Note: In python, We separate the code body of the loop by using indention.

1. Python for loop a tuple


In this code, the item is a variable and num_tuple is a sequence, and print(item) is the code block of for loop that is repeating each element of tuple till the last element of the tuple.

num_tuple = ('A','BC','CD','EF')

print('iterate over each element of a tuple:')

for item in num_tuple:  
  print(item)

Output

iterate over each element of a tuple:
A
BC
CD
EF

2. Python for loop a Dictionary


Here, We are iterating over iterable num_dict dictionary’s key-values pairs using for loop.

num_dict = {'A':65,'BC':67,'CD':68,'EF':69}

print('iterate over each key-value pair of a dictionary:')

for item in num_dict.items() :  

  print(item[0] ,':',item[1])

Output

iterate over each element of a dictionary:
A : 65
BC : 67
CD : 68
EF : 69

3. Python for loop a list or array


Here we are looping the sequence (my_list) using for loop.

my_list= ['A','EF',69]

print('using for loop iterating over each item of a list:')

for item in my_list :  

  print(item)

Output

using for loop iterating over each items of a list:
A
EF
69

4. Python for loop Range()


Unlike other programming languages, Python does not have an in-built numeric loop. So this can be achieved by using Python’s built-in range() function.

Numeric for Loop in C#,Java,C++

for(int i=0;i<5;i++)

The range() function comes in handy, whenever we have to run a for loop for numeric sequence. It can create a sequence of numbers, For example, pass 5 as an argument to range(5), it generates numbers from 0 to 4.

Syntax

range(start,stop,step)
  • Start: start index of number sequence, by default it is 0.
  • End: End index of a numeric sequence, default is the end of the sequence.
  • Step: It represents how many numbers to skip on each iteration by default is 1, it raises ValueError if it is 0.

Example: For loop with range() function

It is a simple example of loop iteration over the sequence 0 to 4.

print('iterate over a sequence of number:')

for item in range(5):  
  print(item)

Output

iterate over a sequence of number:
0
1
2
3
4

Example:For Loop range(start,stop,end)

Here, we have to specify the start, end, step parameter values of range() function, we want to start from index 2 and end on index 10, the number of sequences we are skipping is 2 on each item iteration. It is kind of a step size of 2.

print('iterate sequnce of number with start,stop,end parameter:')

for item in range(2,10,2):  
  print(item)

Output

iterate sequence of number with start, stop, end parameter:
2
4
6
8

5. Python For loop else block


The use of optional else-block with for loop adds more advantage to the python for -loop as compared to other languages. If we need to execute some code after the for-loop terminated then we can use else block with Python for the loop.

For loop with else block

num_list = [2,1,13]

mutiply = 1;
for item in num_list :
        if item != 0:
         mutiply = mutiply * item
        print('mutiplication  :',mutiply)
else:       
        print('loop terminated')

Output

mutiplication  : 2
mutiplication  : 2
mutiplication  : 26
loop terminated

The for…..else block can also be used with a break statement. In this case, if the break terminates the loop, then else block will not execute.

def finditem(num_list):

 item ='A'
 for item in num_list :
        if item  == 'A':         
          print('Item found:',item)
          break
 else:       
        print('no item found:')

#used finditem function
finditem( num_list = ['B','C','A'])

Output

Item found: A

6. Python For loop continue statement


Python also supports continue statements with for loop like other programming languages. If you want to continue the loop, even the condition is true.

num_list = [0,12,0,6,0,3]
mutiply = 1;
 
for item in num_list :
        if item ==0:
          continue  
        mutiply = mutiply*item       
          
   
print('multiplication of non-zero items : ',mutiply)

Output

multiplication of non-zero items :  216