Python Loop Types: For, While, Nested
Python Loop Types: For, While, Nested
Types of Loops
for loops are used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block
of code for each item in the sequence. This is ideal when you know the number of iterations in advance
or are processing elements of a collection.
python
for x in fruits:
print(x)
You can also use the range() function to loop a specific number of times:
python
print("Iteration number:", i)
while loops are used to execute a block of statements repeatedly as long as a given condition remains
true. This is suitable for situations where the number of iterations is not known beforehand, and the
loop continues until a certain condition is met.
python
count = 0
Nested Loops involve placing one loop inside another. The inner loop executes completely for each
iteration of the outer loop.
break: Terminates the loop entirely when a specified condition is met, redirecting program flow to the
statement immediately after the loop.
continue: Skips the current iteration of the loop and moves to the next iteration.
pass: Acts as a placeholder within a loop where a statement is required by syntax but no action is
needed. It does nothing.
For more detailed tutorials and interactive examples, you can refer to resources like W3Schools Python
Loops or the [GeeksforGeeks guide on Python loops]([Link] [Link]/python/loops-in-
python/).
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through
items) and While loops (based on conditions).
For Loop
For loops is used to iterate over a sequence such as a list, tuple, string or range. It allow to execute a
block of code repeatedly, once for each item in the sequence.
n=4
print(i)
Output
Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for loop that iterates over a
range from 0 to n-1 (where n = 4).
Example:
Iterating Over List, Tuple, String and Dictionary Using for Loops in Python
li = ["geeks", "for", "geeks"]
for x in li:
print(x)
for x in tup:
print(x)
s = "abc"
for x in s:
print(x)
d = dict({'x':123, 'y':354})
for x in d:
for x in set1:
print(x),
Output
geeks
for
geeks
geeks
for
geeks
x 123
y 354
10
20
30
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 then iterate over the sequence within the range of this length.
print(li[index])
Output
geeks
for
geeks
Explanation: This code iterates through each element of the list using its index and prints each element
one by one. The range(len(list)) generates indices from 0 to the length of the list minus 1.
orial
Data Types
Interview Questions
Examples
Quizzes
DSA Python
Data Science
NumPy
Pandas
Practice
Open In App
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through
items) and While loops (based on conditions).
For Loop
For loops is used to iterate over a sequence such as a list, tuple, string or range. It allow to execute a
block of code repeatedly, once for each item in the sequence.
n=4
print(i)
Output
Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for loop that iterates over a
range from 0 to n-1 (where n = 4).
Example:
Iterating Over List, Tuple, String and Dictionary Using for Loops in Python
for x in li:
print(x)
print(x)
s = "abc"
for x in s:
print(x)
d = dict({'x':123, 'y':354})
for x in d:
for x in set1:
print(x),
Output
geeks
for
geeks
geeks
for
geeks
c
x 123
y 354
10
20
30
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 then iterate over the sequence within the range of this length.
print(li[index])
Output
geeks
for
geeks
Explanation: This code iterates through each element of the list using its index and prints each element
one by one. The range(len(list)) generates indices from 0 to the length of the list minus 1.
While Loop
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.
In below code, loop runs as long as the condition cnt < 3 is true. It increments the counter by 1 on each
iteration and prints "Hello Geek" three times.
cnt = 0
cnt = cnt + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
If we want a block of code to execute infinite number of times then we can use the while loop in Python
to do so.
Code given below uses a 'while' loop with the condition "True", which means that the loop will run
infinitely until we break out of it using "break" keyword or some other logic.
while (True):
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 we have to forcefully terminate the compiler.
Nested Loops
Python programming language allows to use one loop inside another loop which is called nested loop.
Following example illustrates the concept.
for j in range(i):
print(i, end=' ')
print()
Output
22
333
4444
Explanation: In the above code we use nested loops to print the value of i multiple times in each row,
where the number of times it prints i increases with each iteration of the outer loop. The print() function
prints the value of i and moves to the next line after each row.
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.
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.
continue
Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Explanation: The continue statement is used to skip the current iteration of a loop and move to the next
iteration. It is useful when we want to bypass certain conditions without terminating the loop.
Break Statement
break
Output
Current Letter : e
Explanation: break statement is used to exit the loop prematurely when a specified condition is met. In
this example, the loop breaks when the letter is either 'e' or 's', stopping further iteration.
Pass Statement
We use pass statement in Python to write empty loops. Pass is also used for empty control statements,
functions and classes.
pass
print('Last Letter :', letter)
Output
Last Letter : s
Explanation: In this example, the loop iterates over each letter in 'geeksforgeeks' but doesn't perform
any operation, and after the loop finishes, the last letter ('s') is printed.
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 the loop when the desired condition is met.
Do while loop
Do while loop is a type of control looping statement that can run any statement until the condition
statement becomes false specified in the loop. In do while loop the statement runs at least once no
matter whether the condition is false or true.
do{
// statement or
// set of statements
while(condition)
In this example, we are going to print multiple of 2 using the do while loop. So, that we can understand
the working of do while loop.
#include <iostream>
int main() {
int i=0;
// to write multiple of 2
do{
i++;
cout<<"2 x "<<i<<"="<<2*i<<endl;
}while(i<5);
return 0;
Output: In the below output we can clearly see that program also prints "2 x 5=10" even though 5 is not
less than 5.
2 x 1=2
2 x 2=4
2 x 3=6
2 x 4=8
2 x 5=10
Example 1 :
In this example, we are going to implement the do-while loop in Python using the while loop and if
statement in Python and comparing the while loop with the do-while loop in python.
# initialises a variable
i=0
size = len(list1)
print(list1[i])
i = i+1
i=0
while(True):
print(list1[i])
i = i+1
if(i < size and len(list1[i]) < 10):
continue
else:
break
Output: The while is printing the items in the list. The Do while loop is having two conditions for
terminating.
The pointer of the list reached its last+1 position and any element of the list index having length >=10. In
this code output, we can see that-
The Do While loop is terminated, because the condition len(list1[5])<10 is not fulfilling.
geeksforgeeks
C++
Java
Python
MachineLearning
geeksforgeeks
C++
Java
Python
C
total = 0
while True:
if num == 0:
break
total += num
print("Total:", total)
Output: In this code, we can see that a while loop is running and accepting the input from the user and
adding it. When 0 is entered then it will break out of the loop and print the sum of all numbers which
adds input by the user before 0.
Total: 6
Python Tutorial
Data Types
Interview Questions
Examples
Quizzes
DSA Python
Data Science
NumPy
Pandas
Practice
Open In App
In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted
with the if conditional statements. But Python also allows us to use the else condition with for loops.
The else block just after for/while is executed only when the loop is NOT terminated by a break
statement.
print(i)
print("No Break")
Output :
1
2
No Break
print(i)
break
print("No Break")
Output :
Such type of else is useful only if there is an if condition present inside the loop which somehow
depends on the loop variable.
In the following example, the else statement will only be executed if no element of the array is even, i.e.
if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in
the third iteration of the loop and hence the else present after the for loop is ignored. In the case of
array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed.
# of even number
def contains_even_number(l):
for ele in l:
if ele % 2 == 0:
break
# This else executes only if break is NEVER
else:
# Driver code
contains_even_number([1, 9, 8])
contains_even_number([1, 3, 5])
Output:
For List 1:
For List 2:
count = 0
count = count+1
print(count)
break
else:
print("No Break")
For loop: runs a fixed number of times, usually when you already know how many times you want the
code to repeat.
While loop: runs until a condition becomes false, which is useful when you don’t know in advance how
many times it should run.
Python For Loops are used for iterating over a sequence like lists, tuples, strings and ranges.
For loop allows you to apply the same operation to every item within loop.
Using For Loop avoid the need of manually managing the index.
For loop can iterate over any iterable object, such as dictionary, list or any custom iterators.
for i in s:
print(i)
Output
Geeks
for
Geeks
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.
count = 0
count = count + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
Comparison Table
Now, we will compare both loops in Python to understand where to use 'for loop' and where to use
'while loop'.
For loop
While loop
For loop is used to iterate over a sequence of items.
While loop is used to repeatedly execute a block of statements while a condition is true.
For loops are designed for iterating over a sequence of items. Eg. list, tuple, etc.
While loop is used when the number of iterations is not known in advance or when we want to repeat a
block of code until a certain condition is met.
While the loop requires an initial condition that is tested at the beginning of the loop.
For loop is typically used for iterating over a fixed sequence of items
For loop is more efficient than a while loop when iterating over sequences, since the number of
iterations is predetermined and the loop can be optimized accordingly.
While a loop may be more efficient in certain situations where the condition being tested can be
evaluated quickly.
Python Tutorial
Data Types
Interview Questions
Examples
Quizzes
DSA Python
Data Science
NumPy
Pandas
Practice
Open In App
Using for loop we can iterate a sequence of elements over an iterable like a tuple, list, dictionary, set,
String, etc. A sequence consists of multiple items and this item can be iterated using in keyword and
range keyword in for loop.
A list is used to store the multiple values of the different types under a single variable. It is mutable i.e.,
items in the list can be changed after creation. The list is created by enclosing the data items with square
brackets.
# list creation
for i in a:
print(i)
print('-----')
for i in range(len(a)):
print(a[i])
Output
Geeks
for
Geeks
-----
Geeks
for
Geeks
A tuple is used to store the multiple values of the different types under a single variable. It is immutable
i.e., items in a tuple cannot be changed after creation. A tuple is created by enclosing the data items
with round brackets.
# tuple creation
for i in tup:
print(i)
print('-----')
print(tup[i])
Output
Geeks
for
Geeks
GFG
Learning
Portal
-----
GFG
Learning
Portal
Dictionary is an unordered collection of items where data is stored in key-value pairs. Unlike other data
types like list, set and tuple it holds data as key: value pair. for loop uses in keyword to iterate over each
value in a dictionary.
# dictionary creation
for i in d:
print(i)
Output
A set is an unordered, unindexed, and immutable datatype that holds multiple values under a single
variable. It can be created by surrounding the data items around flower braces or a set method. As the
set is unindexed range method is not used.
# set creation
print(i)
Output
unordered
unindexed
immutable
Here we passed the step variable as 2 in the range method. So we got alternate characters in a string.
# string creation
for i in str:
print(i, end="")
print()
print(str[i], end="_")
Output
GFG Learning-Portal
G_G_L_a_n_n_-_o_t_l_
In Python, loops like for and while are very common for repeating tasks. But sometimes, writing loops
makes the code longer, slower, or harder to read. In many cases, you can eliminate loops by using
Python’s built-in features, which are faster and cleaner.
Eliminate Loops with List Comprehension
A List comprehensions are another way to generate lists without the need for explicit loop structures.
a = []
for i in range(8):
[Link](i**2)
Output
Explanation:
n the first part, a normal for loop is used. It starts with an empty list a and keeps appending each
squared number (i**2) one by one.
In the second part, a list comprehension does the same thing but in a single line: it directly creates a list
of squares of numbers from 0 to 7
The Python itertools modules are a collection of tools for handling iterators. They can eliminate the
need for complex loops and make code more efficient and cleaner.
import itertools
b = []
for sublist in a:
for i in sublist:
[Link](i)
print(b)
b = list([Link](*a))
print(b)
Python Tutorial
Data Types
Interview Questions
Examples
Quizzes
DSA Python
Data Science
NumPy
Pandas
Practice
Open In App
In Python, loops like for and while are very common for repeating tasks. But sometimes, writing loops
makes the code longer, slower, or harder to read. In many cases, you can eliminate loops by using
Python’s built-in features, which are faster and cleaner.
A List comprehensions are another way to generate lists without the need for explicit loop structures.
a = []
for i in range(8):
[Link](i**2)
Output
Explanation:
n the first part, a normal for loop is used. It starts with an empty list a and keeps appending each
squared number (i**2) one by one.
In the second part, a list comprehension does the same thing but in a single line: it directly creates a list
of squares of numbers from 0 to 7
The Python itertools modules are a collection of tools for handling iterators. They can eliminate the
need for complex loops and make code more efficient and cleaner.
import itertools
b = []
for sublist in a:
for i in sublist:
[Link](i)
print(b)
b = list([Link](*a))
print(b)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
You can eliminate loops while working with numerical data, and libraries in Python such as NumPy and
Pandas. These Libraries leverage a technique called Vectorization. It generally performs operations on
the entire array of data.
Let's consider a simple example in which we need to square each number in a list and the range is given
from 1 to 6.
squares = []
[Link](number ** 2)
print(squares)
Output
numbers = [Link](1,6)
squares = numbers ** 2
print(squares)
Output
[ 1 4 9 16 25]
Python's built-in function "map()", "reduce()", and "filter()" provides powerful, functional programming
alternatives to loops.
print(squares)
Python Tutorial
Data Types
Interview Questions
Examples
Quizzes
DSA Python
Data Science
NumPy
Pandas
Practice
▲
Open In App
In Python, loops like for and while are very common for repeating tasks. But sometimes, writing loops
makes the code longer, slower, or harder to read. In many cases, you can eliminate loops by using
Python’s built-in features, which are faster and cleaner.
A List comprehensions are another way to generate lists without the need for explicit loop structures.
a = []
for i in range(8):
[Link](i**2)
Output
Explanation:
n the first part, a normal for loop is used. It starts with an empty list a and keeps appending each
squared number (i**2) one by one.
In the second part, a list comprehension does the same thing but in a single line: it directly creates a list
of squares of numbers from 0 to 7
The Python itertools modules are a collection of tools for handling iterators. They can eliminate the
need for complex loops and make code more efficient and cleaner.
import itertools
b = []
for sublist in a:
for i in sublist:
[Link](i)
print(b)
b = list([Link](*a))
print(b)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
You can eliminate loops while working with numerical data, and libraries in Python such as NumPy and
Pandas. These Libraries leverage a technique called Vectorization. It generally performs operations on
the entire array of data.
Let's consider a simple example in which we need to square each number in a list and the range is given
from 1 to 6.
squares = []
[Link](number ** 2)
print(squares)
Output
numbers = [Link](1,6)
squares = numbers ** 2
print(squares)
Output
[ 1 4 9 16 25]
Python's built-in function "map()", "reduce()", and "filter()" provides powerful, functional programming
alternatives to loops.
print(squares)
Output
[1, 4, 9, 16, 25]
numbers = list(range(1,6))
print(product)
Output
120
"filter()": It creates a list of elements for which the function returns True.
print(even_numbers)
Output
[2, 4]
squares = []
for n in range(50000):
[Link](n ** 2)
print(squares)
Output:
Using for loop: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400,
441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521,
1600,...]
Using generator expression: 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400
441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600.........
In computer Programming, a Loop is used to execute a group of instructions or a block of code multiple
times, without writing it repeatedly. The block of code is executed based on a certain condition.
Share
By the end of this tutorial, you will be able to write and use for loops in various scenarios.
[Featured image] Two coders work on using for loop in python on a monitor and a laptop.
Share
By the end of this tutorial, you will be able to write and use for loops in various scenarios.
[Featured image] Two coders work on using for loop in python on a monitor and a laptop.
Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE)
of your choice (or terminal), stable internet connection
For loops are control flow tools. They are used to iterate over objects or sequences—like lists, strings,
and tuples. You may use a for loop whenever you have a block of code you want to execute repeatedly.
Share
By the end of this tutorial, you will be able to write and use for loops in various scenarios.
[Featured image] Two coders work on using for loop in python on a monitor and a laptop.
Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE)
of your choice (or terminal), stable internet connection
For loops are control flow tools. They are used to iterate over objects or sequences—like lists, strings,
and tuples. You may use a for loop whenever you have a block of code you want to execute repeatedly.
Glossary
Term Definition
Iterate In programming, iteration is the repetition of a code or a process until a specific condition is
met.
Iterables Iterables are objects in Python that you can iterate over.
Control flow Control flow or program flow, is the order of execution in a program’s code.
Control statements In Python, continue, break, and pass are control statements that change the
order of a program’s execution.
Indentation Indentation is the space at the beginning of each line of code. In Python, indentation
indicates a new line of code. In other programming languages, it is used only for readability purposes.
Tuple A tuple is an ordered set of values that is used to store multiple items in just one variable.
else The else statement contains the block of code that will execute if the condition from the if
statement is false or resolves to zero.
break The break command terminates the loop that contains it and redirects the program flow to the
following statement.
continue You can use the keyword continue to end a for loop’s current iteration and continue on
to the next.
pass In Python, pass does nothing. It can be used as a placeholder or to disregard code.
Tell Python you want to create a for loop by starting the statement with for . ...
The for loop in Python is used to iterate over a sequence (like a list, tuple or string) or other iterable
objects. Iterating over a sequence means going through each element one by one. In this article, we're
going to describe how to iterate over a Python list, using the built-in function for.
The for loop, written as [initial] [increment] [limit] { ... } for initializes an internal variable, and executes
the body as long as the internal variable is not more than the limit (or not less, if the increment is
negative) and, at the end of each iteration, increments the internal variable.
In Python, there are three main types of loops: for , while , and nested loops. Let's dive into each of
them, along with their syntax and practical examples.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string). This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.
A loop has four parts. Initialization expression, Test expression, Update expression, The body of the
loop. for loop and while loop is known as Entry controlled loop and do-while loop is known as Exit
controlled loop.
An iteration is the execution of one, or many, lines of code more than once for a certain amount of
repetition (for) or until a condition is met (while)
Iteration: A single execution of the loop body. Infinite Loop: A loop that never terminates because the
condition is always true. (This is usually a bug!)
A for loop has two parts: a header specifying the iteration, and a body which is executed once per
iteration. The header often declares an explicit loop counter or loop variable, which allows the body to
know which iteration is being executed.
In Python, the two most common loops are the For loop and the While loop. Both these loops help in
iteration but work differently and have different use cases
for loop
The for loop is probably the most common and well known type of loop in any programming language.
For can be used to iterate through the elements of an array: For can also be used to perform a fixed
number of iterations: By default the increment is one.
You use the break statement in Python to immediately exit a loop, allowing the program to continue
executing the code that follows the loop.
hang, which means that it just sits there and does nothing.
continue prompting the user forever and never letting them end the program.
Loop Operation: the loop runs the body lines again and again, once for each element in the collection.
Each run of the body is called an "iteration" of the loop. For the first iteration, the variable is set to the
first element, and the body lines run (in this case, essentially num = 2 .
An implied loop in map() is faster than an explicit for loop; a while loop with an explicit loop counter is
even slower. Avoid calling functions written in Python in your inner loop. This includes lambdas. In-lining
the inner loop can save a lot of time.
A while loop is a type of loop that repeats a block of code while a specific condition is true.