Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Advanced Python List Methods and Techniques
Next article icon

Looping Techniques in Python

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Python supports various looping techniques by certain inbuilt functions, in various sequential containers. These methods are primarily very useful in competitive programming and also in various projects that require a specific technique with loops maintaining the overall structure of code.  A lot of time and memory space is been saved as there is no need to declare the extra variables which we declare in the traditional approach of loops.

Where they are used?

Different looping techniques are primarily useful in places where we don’t need to actually manipulate the structure and order of the overall containers, rather only print the elements for a single-use instance, no in-place change occurs in the container. This can also be used in instances to save time.

Different looping techniques using Python data structures  are: 

Way 1: Using enumerate():  enumerate() is used to loop through the containers printing the index number along with the value present in that particular index.

Python3




# python code to demonstrate working of enumerate()
 
for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']):
    print(key, value)
 
 

Output:

0 The
1 Big
2 Bang
3 Theory

Python3




# python code to demonstrate working of enumerate()
 
for key, value in enumerate(['Geeks', 'for', 'Geeks',
                             'is', 'the', 'Best',
                             'Coding', 'Platform']):
    print(value, end=' ')
 
 

Output:

Geeks for Geeks is the Best Coding Platform 

Way 2: Using zip(): zip() is used to combine 2 or more containers printing the values sequentially. The loop exists only till the smaller container ends. A detailed explanation of zip() and enumerate() can be found here.

Example 1: Two different data type(list,tuple)

Python




# python code to demonstrate working of zip()
 
names = ['Deep', 'Sachin', 'Simran']        # list
ages = (24, 27, 25)           # tuple
 
for name, age in zip(names, ages):
    print('Name: ', name)
    print('Age: ', age)
    print()
 
 
Output
('Name: ', 'Deep') ('Age: ', 24) () ('Name: ', 'Sachin') ('Age: ', 27) () ('Name: ', 'Simran') ('Age: ', 25) () 

Example 2: Two similar datatype list-list

Python3




# python code to demonstrate working of zip()
 
# initializing list
questions = ['name', 'colour', 'shape']
answers = ['apple', 'red', 'a circle']
 
# using zip() to combine two containers
# and print values
for question, answer in zip(questions, answers):
    print('What is your {0}?  I am {1}.'.format(question, answer))
 
 

Output:

What is your name?  I am apple.
What is your color? I am red.
What is your shape? I am a circle.

Way 3: Using iteritem(): iteritems() is used to loop through the dictionary printing the dictionary key-value pair sequentially which is used before Python 3 version.

Way 4: 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 a dictionary.

Example 1:

Python3




# python code to demonstrate working of items()
 
d = {"geeks": "for", "only": "geeks"}
 
# iteritems() is renamed to items() in python3
# using items to print the dictionary key-value pair
print("The key value pair using items is : ")
for i, j in d.items():
    print(i, j)
 
 

Output:

The key value pair using iteritems is : 
geeks for
only geeks

Example 2:

Python3




# python code to demonstrate working of items()
 
king = {'Ashoka': 'The Great', 'Chandragupta': 'The Maurya',
        'Modi': 'The Changer'}
 
# using items to print the dictionary key-value pair
for key, value in king.items():
    print(key, value)
 
 
Output
Ashoka The Great Chandragupta The Maurya Modi The Changer 

Way 5: 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. The use of set() can be combined to remove duplicate occurrences.

Example 1:

Python3




# python code to demonstrate working of sorted()
 
# initializing list
lis = [1, 3, 5, 6, 2, 1, 3]
 
# using sorted() to print the list in sorted order
print("The list in sorted order is : ")
for i in sorted(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 : ")
for i in sorted(set(lis)):
    print(i, end=" ")
 
 

Output:

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:

Python3




# python code to demonstrate working of sorted()
 
# initializing list
basket = ['guave', 'orange', 'apple', 'pear',
          'guava', 'banana', 'grape']
 
# using sorted() and set() to print the list
#  in sorted order
for fruit in sorted(set(basket)):
    print(fruit)
 
 

Output:

apple
banana
grape
guava
guave
orange
pear

Way 6: Using reversed(): reversed() is used to print the values of the container in the reversed order. It does not reflect any changes to the original list

Example 1:

Python3




# python code to demonstrate working of reversed()
 
# initializing list
lis = [1, 3, 5, 6, 2, 1, 3]
 
 
# using reversed() to print the list in reversed order
print("The list in reversed order is : ")
for i in reversed(lis):
    print(i, end=" ")
 
 

Output:

The list in reversed order is : 
3 1 2 6 5 3 1

Example 2:

Python3




# python code to demonstrate working of reversed()
 
# using reversed() to print in reverse order
for i in reversed(range(1, 10, 3)):
    print(i)
 
 

Output:

7
4
1
  • These techniques are quick to use and reduce coding effort. for, while loops need the entire structure of the container to be changed.
  • These Looping techniques do not require any structural changes to the container. They have keywords that present the exact purpose of usage. Whereas, no pre-predictions or guesses can be made in for, while loop i.e not easily understand the purpose at a glance.
  • Looping technique makes the code more concise than using for & while looping.

looping techniques  while loop using if statements:

In this example, we use a while loop to increment a variable called count. Inside the loop, we use an if statement to check if count is equal to 3. If it is, we print a message.

Approach:

Initialize a count variable to 0
Use a while loop to repeatedly execute a block of code as long as count is less than 5
Inside the loop, use an if statement to check if count is equal to 3
If count is 3, print a message
Increment the count by 1 at the end of each iteration

Python3




# Example variable
count = 0
 
# Loop while count is less than 5
while count < 5:
    if count == 3:
        print("Count is 3")
    count += 1
 
 
Output
Count is 3  

Time complexity: O(n), where n is the number of iterations required for count to reach 5.

Auxiliary Space: O(1), since only one variable (count) is used throughout the code.



Next Article
Advanced Python List Methods and Techniques
author
kartik
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Python While Loop
    Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. In this example, the condition for while will be True as long as the counter variable (count)
    5 min read
  • Python Do While Loops
    In Python, there is no construct defined for do while loop. Python loops only include for loop and while loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java. In Python, we can simulate the behavior of a do-while loop using a while loop with a cond
    6 min read
  • Advanced Python List Methods and Techniques
    Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and
    6 min read
  • Different Input and Output Techniques in Python3
    An article describing basic Input and output techniques that we use while coding in python. Input Techniques 1. Taking input using input() function -> this function by default takes string as input. Example: C/C++ Code #For string str = input() # For integers n = int(input()) # For floating or de
    3 min read
  • Update List in Python
    In Python Programming, a list is a sequence of a data structure that is mutable. This means that the elements of a list can be modified to add, delete, or update the values. In this article we will explore various ways to update the list. Let us see a simple example of updating a list in Python. [GF
    3 min read
  • Write your own len() in Python
    The method len() returns the number of elements in the list or length of the string depending upon the argument you are passing. How to implement without using len(): Approach: Take input and pass the string/list into a function which return its length.Initialize a count variable to 0, this count va
    2 min read
  • Understanding for-loop in Python
    A Pythonic for-loop is very different from for-loops of other programming language. A for-loop in Python is used to loop over an iterator however in other languages, it is used to loop over a condition. In this article, we will take a deeper dive into Pythonic for-loop and witness the reason behind
    6 min read
  • Jump Statements in Python
    In any programming language, a command written by the programmer for the computer to act is known as a statement. In simple words, a statement can be thought of as an instruction that programmers give to the computer and upon receiving them, the computer acts accordingly. There are various types of
    4 min read
  • Decrement in While Loop in Python
    A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article
    3 min read
  • Python - Itertools.takewhile()
    The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easy. One such itertools function is takewhile(). Note: For more information, refer to Python Itertools takewhile() This al
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences