Looping Techniques in Python
Python supports various looping techniques by certain inbuilt functions, in various sequential containers. These methods are primarily verya useful in competitive programming and also in various project which require a specific technique with loops maintaining the overall structure of code.
Where they are used ?
Different looping techniques are primarily useful in the places where we don’t need to actually manipulate the structure and ordering of overall container, rather only print the elements for a single use instance, no inplace change occurs in the container. This can also be used in instances to save time.
Different looping techniques using Python data structures are:
- Using enumerate(): enumerate() is used to loop through the containers printing the index number along with the value present in that particular index.
# python code to demonstrate working of enumerate()forkey, valueinenumerate(['The','Big','Bang','Theory']):print(key, value)chevron_rightfilter_noneOutput :
0 The 1 Big 2 Bang 3 Theory
- Using zip(): zip() is used to combine 2 similar containers(list-list or dict-dict) printing the values sequentially. The loop exists only till the smaller container ends. The detailed explanation of zip() and enumerate() can be found here.
# python code to demonstrate working of zip()# initializing listquestions=['name','colour','shape']answers=['apple','red','a circle']# using zip() to combine two containers# and print valuesforquestion, answerinzip(questions, answers):print('What is your {0}? I am {1}.'.format(question, answer))chevron_rightfilter_noneOutput :
What is your name? I am apple. What is your color? I am red. What is your shape? I am a circle.
- Using iteritem(): iteritems() is used to loop through the dictionary printing the dictionary key-value pair sequentially.
- Using items(): items() performs the similar task on dictionary as iteritems() but have certain disadvantages when compared with iteritems().
- It is very time consuming. Calling it on large dictionaries consumes quite a lot of time.
- It takes a lot of memory. Sometimes takes double the memory when called on dictionary.
- Example 1:
# python code to demonstrate working of iteritems(),items()d={"geeks":"for","only":"geeks"}# using iteritems to print the dictionary key-value pairprint("The key value pair using iteritems is : ")fori,jind.iteritems():printi,j# using items to print the dictionary key-value pairprint("The key value pair using items is : ")fori,jind.items():printi,jchevron_rightfilter_noneOutput:
The key value pair using iteritems is : geeks for only geeks The key value pair using items is : geeks for only geeks
- Example 2:
# python code to demonstrate working of items()king={'Akbar':'The Great','Chandragupta':'The Maurya','Modi':'The Changer'}# using items to print the dictionary key-value pairforkey, valueinking.items():print(key, value)chevron_rightfilter_noneOutput :
Akbar The Great Modi The Changer Chandragupta The Maurya
- Using sorted(): sorted() is used to print the container is sorted order. It doesn’t sort the container, but just prints the container in sorted order for 1 instance. Use of set() can be combined to remove duplicate occurrences.
- Example 1:
# python code to demonstrate working of sorted()# initializing listlis=[1,3,5,6,2,1,3]# using sorted() to print the list in sorted orderprint("The list in sorted order is : ")foriinsorted(lis) :print(i,end=" ")print("\r")# using sorted() and set() to print the list in sorted order# use of set() removes duplicates.print("The list in sorted order (without duplicates) is : ")foriinsorted(set(lis)) :print(i,end=" ")chevron_rightfilter_noneOutput:
The list in sorted order is : 1 1 2 3 3 5 6 The list in sorted order (without duplicates) is : 1 2 3 5 6
- Example 2:
# python code to demonstrate working of sorted()# initializing listbasket=['guave','orange','apple','pear','guava','banana','grape']# using sorted() and set() to print the list# in sorted orderforfruitinsorted(set(basket)):print(fruit)chevron_rightfilter_noneOutput:
apple banana grape guava guave orange pear
- Using reversed(): reversed() is used to print the values of container in the descending order as declared.
- Example 1:
# python code to demonstrate working of reversed()# initializing listlis=[1,3,5,6,2,1,3]# using revered() to print the list in reversed orderprint("The list in reversed order is : ")foriinreversed(lis) :print(i,end=" ")chevron_rightfilter_noneOutput:
The list in reversed order is : 3 1 2 6 5 3 1
- Example 2:
# python code to demonstrate working of reversed()# using reversed() to print in reverse orderforiinreversed(range(1,10,3)):print(i)chevron_rightfilter_noneOutput :
7 4 1
- These techniques are quick to use and reduces coding effort. for, while loops needs the entire structure of container to be changed.
- These Looping techniques do not require any structural changes to container. They have keywords which present the exact purpose of usage. Whereas, no pre-predictions or guesses can be made in for, while loop i.e not easily understandable the purpose at a glance.
- Looping technique make the code more concise than using for, while loopings.
- Short Circuiting Techniques in Python
- Types of Regression Techniques
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- SQL using Python | Set 1
- try and except in Python
- pow() in Python
- Python | a += b is not always a = a + b
- chr() in Python
- zip() in Python
- abs() in Python
- gcd() in Python
- max() and min() in Python
- Python Set | pop()
-
Note: iteritems() has been removed from the python 3.x it only works in python 2.x.Instead use dict.items().
Advantage of using above techniques over for, while loop
References : https://docs.python.org/3/tutorial/datastructures.html#looping-techniques
This article is contributed by Manjeet Singh and Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
Improved By : raishivamsm



