Python Looping Techniques

In this tutorial, we are going to learn various looping techniques provided by Python. Python supports various inbuilt functions that perform looping mechanism like any other programming language.

Python is a high level, dynamic programming language and thus provides the shortcode and more flexibility. Hence it is easy to apply looping techniques in Python. Because looping is one of the most important operations in the programming world, Python provides various containers to perform these operations. Containers are the data structure in Python. We use this technique in order to run the task repeatedly and sequentially for a single-use instance.

However, Python has an inbuilt function that gives us more flexibility to perform looping. We will go through each of these functions and see how these functions can be put into action.

Python Looping Techniques

Let’s start…

Different techniques of looping are:

1. Enumerate – It is used to loop through the container such as a list which is an ordered collection of data. It returns the index and value of that index.

for key, value in enumerate(list(range(100)): 
    print(key, value)

2. zip – It combines two containers of the same type for eg. list-to-list and dict-to-dict and returns two values one from each container sequentially.

list1= ['id', 'name', 'age']
list2= ['123', 'Aman', 60]
for x, y in zip(list1, list2):
    print('What is your {0}?  - {1}.'.format(x, y))

3. items – It iterates through dictionary containers and return key-value pairs sequentially.
4. iteritems – It is similar to the iteritems except it is slightly faster than the items method. It is useful when there is a long dictionary. This function requires less memory than the items method. This method is removed in Python3 but works for Python versions below 3.

dict = { "codespeedy" : "internship", "for" : "students" } 
print ("The key value pair using iteritems is : ") 
for i,j in dict.iteritems(): ## for python python version below 3.
print ("The key value pair using items is : ") ## works for python3 and above.
for i,j in dict.items(): 

5. Sorted – It returns the values in sorted order from the containers. set() can be used to remove the duplicate values.

import random
#Generate 5 random numbers between 10 and 30
unsorted_list = random.sample(range(10, 30), 5)


print ("sorted list is : ")
for i in sorted(unsorted_list) :
    print (i,end=" ")

print ("\nsorted list without duplicates is : ")
for i in sorted(set(unsorted_list)) :
    print (i,end=" ")

6. reversed – It is used to return the values in reverse order from the container.

print ("The list in reversed order is : ") 
for i in reversed(unsorted_list) : 
    print (i,end=" ")


Leave a Reply

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