Open In App

Loops in Python – For, While and Nested Loops

Last Updated : 13 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp – For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops.

While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time. In this article, we will look at Python loops and understand their working with the help of examples.

While Loop in Python

In Python, a 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.

Python While Loop Syntax:

while expression:
statement(s)

All the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. 

Let’s learn how to use a while loop in Python with Examples:

Example of Python While Loop 

Let’s see a simple example of a while loop in Python. The given Python code uses a while' loop to print “Hello Geek” three times by incrementing a variable called count' from 1 to 3.

Python
count = 0
while (count < 3):
    count = count + 1
    print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello Geek

Using else statement with While Loop in Python

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed. 

Syntax of While Loop with else statement:

while condition:
# execute these statements
else:
# execute these statements

Here is an example of while loop with else statement in Python:

The code prints “Hello Geek” three times using a while' loop and then, after the loop, it prints “In Else Block” because there is an “else” block associated with the while' loop.

Python
count = 0
while (count < 3):
    count = count + 1
    print("Hello Geek")
else:
    print("In Else Block")

Output
Hello Geek
Hello Geek
Hello Geek
In Else Block

Infinite While Loop in Python

If we want a block of code to execute infinite number of time, we can use the while loop in Python to do so.

The code uses a while' loop with the condition (count == 0). This loop will only run as long as count is equal to 0. Since count is initially set to 0, the loop will execute indefinitely because the condition is always true.

Python
count = 0
while (count == 0):
    print("Hello Geek")

Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the condition is always true and you have to forcefully terminate the compiler.

For Loop in Python

For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is “for in” loop which is similar to foreach loop in other languages. Let us learn how to use for loops in Python for sequential traversals with examples.

For Loop Syntax:

for iterator_var in sequence:
statements(s)

It can be used to iterate over a range and iterators.

Example:

The code uses a Python for loop that iterates over the values from 0 to 3 (not including 4), as specified by the range(0, n) construct. It will print the values of i' in each iteration of the loop.

Python
n = 4
for i in range(0, n):
    print(i)

Output
0
1
2
3

Example with List, Tuple, String, and Dictionary Iteration Using for Loops in Python

We can use for loop to iterate lists, tuples, strings and dictionaries in Python.

The code showcases different ways to iterate through various data structures in Python. It demonstrates iteration over lists, tuples, strings, dictionaries, and sets, printing their elements or key-value pairs.

The output displays the contents of each data structure as it is iterated.

Python
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
    print(i)
    
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
    print(i)
    
print("\nString Iteration")
s = "Geeks"
for i in s:
    print(i)
    
print("\nDictionary Iteration")
d = dict({'x':123, 'y':354})
for i in d:
    print("%s  %d" % (i, d[i]))
    
print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
    print(i),

Output
List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz  123
abc  345

Set Iteration
1
2
3
4
5
6

Iterating by the Index of Sequences

We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length. See the below

Example: This code uses a for' loop to iterate over a list and print each element. It iterates through the list based on the index of each element, obtained using range(len(list))'. The result is that it prints each item in the list on separate lines.

Python
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
    print(list[index])

Output
geeks
for
geeks

Using else Statement with for Loop in Python

We can also combine else statement with for loop like in while loop. But as there is no condition in for loop based on which the execution will terminate so the else block will be executed immediately after for block finishes execution. 

In this code, the for' loop iterates over a list and prints each element, just like in the previous example. However, after the loop is finished, the “else” block is executed. So, in this case, it will print “Inside Else Block” once the loop completes.

Python
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
    print(list[index])
else:
    print("Inside Else Block")

Output
geeks
for
geeks
Inside Else Block

Nested Loops in Python

Python programming language allows to use one loop inside another loop which is called nested loop. Following section shows few examples to illustrate the concept. 

Nested Loops Syntax:

for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in the Python programming language is as follows: 

while expression:
while expression:
statement(s)
statement(s)

A final note on loop nesting is that we can put any type of loop inside of any other type of loops in Python. For example, a for loop can be inside a while loop or vice versa.

Example: This Python code uses nested for' loops to create a triangular pattern of numbers. It iterates from 1 to 4 and, in each iteration, prints the current number multiple times based on the iteration number. The result is a pyramid-like pattern of numbers.

Python
from __future__ import print_function
for i in range(1, 5):
    for j in range(i):
        print(i, end=' ')
    print()

Output
1 
2 2 
3 3 3 
4 4 4 4 

Loop Control Statements

Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements. 

Continue Statement

The continue statement in Python returns the control to the beginning of the loop.

Example: This Python code iterates through the characters of the string ‘geeksforgeeks’. When it encounters the characters ‘e’ or ‘s’, it uses the continue statement to skip the current iteration and continue with the next character. For all other characters, it prints “Current Letter :” followed by the character. So, the output will display all characters except ‘e’ and ‘s’, each on a separate line.

Python
for letter in 'geeksforgeeks':
    if letter == 'e' or letter == 's':
        continue
    print('Current Letter :', letter)

Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Break Statement

The break statement in Python brings control out of the loop.

Example: In this Python code, it iterates through the characters of the string ‘geeksforgeeks’. When it encounters the characters ‘e’ or ‘s’, it uses the break statement to exit the loop. After the loop is terminated, it prints “Current Letter :” followed by the last character encountered in the loop (either ‘e’ or ‘s’). So, the output will display “Current Letter :” followed by the first occurrence of ‘e’ or ‘s’ in the string.

Python
for letter in 'geeksforgeeks':
    if letter == 'e' or letter == 's':
        break

print('Current Letter :', letter)

Output
Current Letter : e

Pass Statement

We use pass statement in Python to write empty loops. Pass is also used for empty control statements, functions and classes.

Example: This Python code iterates through the characters of the string ‘geeksforgeeks’ using a for' loop. However, it doesn’t perform any specific action within the loop, and the pass' statement is used. After the loop, it prints “Last Letter :” followed by the last character in the string, which is ‘s’.

Python
for letter in 'geeksforgeeks':
    pass
print('Last Letter :', letter)

Output
Last Letter : s

How for loop works internally in Python?

Before proceeding to this section, you should have a prior understanding of Python Iterators.

Firstly, lets see how a simple for loops in Python looks like.

Example: This Python code iterates through a list called fruits, containing “apple”, “orange” and “kiwi.” It prints each fruit name on a separate line, displaying them in the order they appear in the list.

Python
fruits = ["apple", "orange", "kiwi"]

for fruit in fruits:

    print(fruit)

Here we can see the for loops that iterates over iterable object fruit which is a list. Lists, sets, dictionaries are few iterable objects while an integer object is not an iterable object. For loops can iterate over any of these iterable objects.

This Python code manually iterates through a list of fruits using an iterator. It prints each fruit’s name one by one and stops when there are no more items in the list.

Python
fruits = ["apple", "orange", "kiwi"]
iter_obj = iter(fruits)
while True:
    try:
        fruit = next(iter_obj)
        print(fruit)
    except StopIteration:
        break

Output
apple
orange
kiwi

We can see that under the hood we are calling iter() and next() method. 

We have covered Python Loops in this article. We also saw how to use for loop, while loop and nested loop in Python. This article provides different use-case scenarios and examples to demonstrate working of loops and give clear understanding.

Learn More on Loops:

Python Loops – FAQs

Which loop is faster in Python?

In general, for loops tend to be faster than while loops in Python due to the way they are implemented. However, the difference in performance between for and while loops is often negligible for most practical purposes. The choice between them should be based on clarity and suitability for the specific task rather than performance concerns.

Why is Python slow in loops?

Python can be perceived as slow in loops when compared to lower-level languages like C or C++. This is primarily because Python is an interpreted language, meaning that each line of code is executed one by one at runtime. Additionally, Python’s dynamic typing and memory management can introduce overhead compared to statically-typed compiled languages.

How many loops are used in Python?

Python supports several types of loops:

  • for loop: Iterates over a sequence (e.g., list, tuple, string, dictionary).
  • while loop: Executes a block of code as long as a specified condition is true.
  • Nested loops: One loop inside another loop.
  • Comprehensions (e.g., list comprehensions, dictionary comprehensions): Concise ways to create lists, dictionaries, etc., using loops.

How to improve Python loops?

To optimize loops in Python, consider the following tips:

  • Use list comprehensions: They are often faster than traditional for loops for creating lists.
  • Minimize function calls: Move function calls outside loops if possible.
  • Use built-in functions: Python’s built-in functions (e.g., map(), filter(), sum()) are optimized and can be faster than manually written loops.
  • Profile your code: Use tools like cProfile to identify bottlenecks and optimize accordingly.
  • Consider using libraries: Libraries like NumPy and pandas offer optimized functions for common tasks involving loops over arrays or data frames.

Is for loop bad in Python?

No, for loops are not inherently bad in Python. They are a fundamental construct for iteration and are widely used in Python programming. However, for certain tasks involving large datasets or performance-critical code, optimizing loop operations using techniques like list comprehensions, vectorized operations (in libraries like NumPy), or reducing function calls can improve efficiency.



Next Article

Similar Reads

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 condition that is initially True and then break out of
6 min read
How to make a box with the help of nested loops using Python arcade?
Arcade library is modern framework currently used in making 2D games. Nested loop discussed here are analogous to nested loops in any other programming language. The following tutorial will step by step explain how to draw a box with the help of nested loops using Python's arcade module. Import arcade library.Here we will be using circles to form a
2 min read
Python Nested Loops
In Python programming language there are two types of loops which are for loop and while loop. Using these loops we can create nested loops in Python. Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc. Python Nested Loops Syntax:Outer_loop Expression:     Inner_loop Expression:
9 min read
Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read
Loops and Control Statements (continue, break and pass) in Python
Python programming language provides the following types of loops to handle looping requirements. Python While Loop Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false. Syntax of Python Whilewhile
4 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
When not to use Recursion while Programming in Python?
To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely. Say, we need to create a function which when called needs to print the data in a linked list. This can be done in 2 w
3 min read
How to use while True in Python
In this article, we will discuss how to use while True in Python. While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever. Example: While Loop with True C/C++ Code # Python program to demonstrate # while loop with True while True: pass If we run
2 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 will see how to decrement in while loop in Python.
3 min read
Python While Else
Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss the "while-else" loop in detail with examples. Wha
6 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
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. Syntax of while loop in Pythonwhile expression: statement(s)Flowchart of Python While Loop While loop falls under the category of indefinite ite
9 min read
How to fix "error 403 while installing package with Python PIP"?
When working with Python, pip is the go-to tool for managing packages. However, encountering a "403 Forbidden" error can be frustrating. This error typically indicates that the server refuses to fulfill the request, often due to permissions or access restrictions. In this article, we'll delve into the causes of this error and explore various soluti
4 min read
How to Disable Logging While Running Unit Tests in Python Django
It is never necessary to log everything while testing because it may flood the terminal with unnecessary log messages. These logs are useful during development but can be distracting when focusing on the actual test results. Disabling logging during unit tests can make our output cleaner and easier to understand. There are different ways to disable
4 min read
Specifying the increment in for-loops in Python
Let us see how to control the increment in for-loops in Python. We can do this by using the range() function. range() function range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well
2 min read
Use for Loop That Loops Over a Sequence in Python
In this article, we are going to discuss how for loop is used to iterate over a sequence in Python. Python programming is very simple as it provides various methods and keywords that help programmers to implement the logic of code in fewer lines. Using for loop we can iterate a sequence of elements over an iterable like a tuple, list, dictionary, s
3 min read
Python For Loops
The For Loops in Python are a special type of loop statement that is used for sequential traversal. Python For loop is used for iterating over an iterable like a String, Tuple, List, Set, or Dictionary. For Loop Example: [GFGTABS] Python s = "Geeks" # using for loop with string for i in s: print(i) [/GFGTABS] Table of Content How to use t
8 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
How to preserve Function Metadata while using Decorators?
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.Note: For more information, refer Decorators in Python How to preserve Metadata? This
2 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
7 Mistakes You Should Avoid While Building a Django Application
Django...We all know the popularity of this Python framework. Django has become the first choice of developers to build their web applications. It is a free and open-source Python framework. Django can easily solve a lot of common development challenges. It allows you to build flexible and well-structured web applications. A lot of common features
6 min read
How to not get caught while web scraping ?
In this article, we are going to discuss how to not get caught while web scraping. Let's look at all such alternatives in detail: Robots.txtIt is a text file created by the webmaster which tells the search engine crawlers which pages are allowed to be crawled by the bot, so it is better to respect robots.txt before scraping.Example: Here GFG's robo
5 min read
Protecting sensitive information while deploying Django project
There will be a lot of sensitive information in our Django project resided in the settings.py, or local variables containing sensitive information or the POST request made using forms. So while deploying a Django project we always have to make sure they are protected especially the repositories that are publicly available. When a project is deploye
3 min read
Pyspark dataframe: Summing column while grouping over another
In this article, we will discuss how to sum a column while grouping another in Pyspark dataframe using Python. Let's create the dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSe
4 min read
How to Remove Index Column While Saving CSV in Pandas
In this article, we'll discuss how to avoid pandas creating an index in a saved CSV file. Pandas is a library in Python where one can work with data. While working with Pandas, you may need to save a DataFrame to a CSV file. The Pandas library includes an index column in the output CSV file by default. Further in the article, we'll understand the d
3 min read
PyQt5 - How to automate Progress Bar while downloading using urllib?
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps. In this article, we will learn how to automate the Progress Bar
3 min read
Avoid these mistakes while preparing for the CAT Exam
The CAT exam is arguably the most important exam in India for students wanting to secure the coveted MBA seats in various management institutes of the country. This is obvious from the high level of competition with more than two lakh candidates competing for seats in various MBA programs such as Finance, Marketing, Operations, etc. and only 11 can
6 min read
Python Nested Dictionary
A Dictionary in Python works similarly to the Dictionary in the real world. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. What is Python in Nested Dictionary? Nesting Dictionary means putting a dictionary inside another dictionary. Ne
3 min read
Python | Intersection of two nested list
This particular article aims at achieving the task of intersecting two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task. Method 1: Naive Method This is the simplest method to achieve thi
5 min read
Python | Cumulative Nested Tuple Column Product
Sometimes, while working with records, we can have a problem in which we require to perform index wise multiplication of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using zip() + nested generator expression The
7 min read
Article Tags :
Practice Tags :
  翻译: