Loops in Python – For, While and Nested Loops
Last Updated :
13 Feb, 2025
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. 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.
Example of Python While Loop:
Python
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")
OutputHello Geek
Hello Geek
Hello Geek
Using else statement with While Loop in Python
Else clause is only executed when our while condition becomes false. If we break out of the loop or if an exception is raised then it won’t be executed.
Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
Example:
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
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")
else:
print("In Else Block")
OutputHello 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 times then we can use the while loop in Python to do so.
The code given below uses a ‘while’ loop with the condition (count == 0) and 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 we 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)
Python
n = 4
for i in range(0, n):
print(i)
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 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.
Python
li = ["geeks", "for", "geeks"]
for i in li:
print(i)
tup = ("geeks", "for", "geeks")
for i in tup:
print(i)
s = "Geeks"
for i in s:
print(i)
d = dict({'x':123, 'y':354})
for i in d:
print("%s %d" % (i, d[i]))
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Outputgeeks
for
geeks
geeks
for
geeks
G
e
e
k
s
x 123
y 354
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.
Python
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
print(list[index])
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.
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.
Python
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")
Outputgeeks
for
geeks
Inside Else Block
Explanation: The code iterates through the list and prints each element. After the loop ends it prints “Inside Else Block” as the else block executes when the loop completes without a break.
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.
Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output1
2 2
3 3 3
4 4 4 4
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.
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.
Python
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
OutputCurrent 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
The break statement in Python brings control out of the loop.
Python
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
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.
Python
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
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.
How for loop works internally in Python?
Before proceeding to this section, we 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)
This code iterates over each item in the fruits list and prints the item (fruit) on each iteration and the output will display each fruit on a new line.
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
We can see that under the hood we are calling iter() and next() method.
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 our 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.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial - Python is one of the most popular programming languages today, known for its simplicity, extensive features and library support. Its clean and straightforward syntax makes it beginner-friendly, while its powerful libraries and frameworks makes it perfect for developers. Python is:
9 min read
Getting Started with Python Programming
To get started with Python, let's first finish the installation steps. Here's a basic guide to setup Python in your system. Install PythonBefore starting this Python course first, you need to install Python on your computer. To install Python on your computer, follow these steps: Download Python: Go
2 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Printing Output using print() in PythonAt its co
7 min read
Data Types
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1. [GFGTABS] Python s = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # updat
5 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
5 min read
Python Tuples
A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
7 min read
Python Sets
Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change. Creating a Set in PythonIn Python, the most basic and efficient method for creatin
11 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
Python Arrays
Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences: Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Conditional Statements in Python
Conditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations. If Conditional Statement in PythonIf statement is the simplest form of a conditional st
6 min read
Loops in Python - For, While and Nested Loops
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in th
9 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
10 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read