Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- String Formatting
- Indexing and Slicing
- Set Comprehensions
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Python Core Concepts
Python Collections
- Python collections ChainMap
- Python collections
- Python collections ChainMap<
- Python counters
- Python deque
- Python dictionary
- Python Lists
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Nested Loops in Python
Looping is a foundational concept in programming that allows you to execute a block of code repeatedly. But what if you need to perform a loop inside another loop? Thatโs where nested loops come in. If youโre just starting out in Python, understanding nested loops can open the door to solving more complex problems like matrix manipulation, pattern printing, or building simple games.
In this guide, weโll take a deep dive into nested loops in Python, exploring what they are, why they matter, and how to use them with real-world, easy-to-understand examples.
๐ Why Are Nested Loops Important?
Nested loops give you multi-layered control over repetitive operations. They are crucial for:
- Working with multi-dimensional data like matrices or tables
- Pattern generation, such as pyramid or star shapes
- Comparing pairs of data
- Iterating through nested structures like lists of lists
Without nested loops, many tasks would require unnecessarily complex or repetitive code.
โ Prerequisites
Before tackling nested loops, ensure you understand:
- Basic
for
andwhile
loops - Indentation in Python (crucial for nesting)
- Data structures like lists and strings
- Boolean conditions and loop control statements
๐ What This Guide Covers
- What are nested loops?
- Syntax of nested loops
- Types of nested loops (
for
infor
,for
inwhile
, etc.) - Real-world examples and use cases
- Common mistakes to avoid
- Best practices for beginners
๐ What Are Nested Loops?
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.
๐ General Syntax:
for outer in range(x):
for inner in range(y):
# Code block executed y times for each outer iteration
This means if x = 3
and y = 2
, the inner block runs 3 ร 2 = 6
times.
๐ Types of Nested Loops
Python allows nesting any combination of loops:
for
loop inside afor
loopfor
loop inside awhile
loopwhile
loop inside afor
loopwhile
loop inside anotherwhile
loop
Letโs go over each.
โ 1. For Loop Inside a For Loop
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
This loop runs 2
inner iterations for every 1
outer iteration.
โ 2. While Loop Inside a For Loop
for i in range(3):
j = 0
while j < 2:
print(f"i={i}, j={j}")
j += 1
Same output as above. It just mixes loop types.
โ 3. For Loop Inside a While Loop
i = 0
while i < 2:
for j in range(3):
print(f"i={i}, j={j}")
i += 1
Output:
i=0, j=0
i=0, j=1
i=0, j=2
i=1, j=0
i=1, j=1
i=1, j=2
โ 4. While Loop Inside Another While Loop
i = 0
while i < 2:
j = 0
while j < 3:
print(f"i={i}, j={j}")
j += 1
i += 1
Same outputโloop nesting can be flexible in Python.
๐ Real-World Examples of Nested Loops
๐ Example 1: Printing a Rectangle of Stars
for row in range(4):
for col in range(5):
print("*", end=" ")
print()
Output:
* * * * *
* * * * *
* * * * *
* * * * *
๐ Example 2: Multiplication Table
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end="\t")
print()
Prints a 5ร5 multiplication table.
๐ Example 3: Working with 2D Lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for item in row:
print(item, end=" ")
print()
Output:
1 2 3
4 5 6
7 8 9
๐ Example 4: Comparing All Pairs in a List
nums = [1, 2, 3]
for i in nums:
for j in nums:
print(f"({i}, {j})")
Useful in algorithms and data comparison tasks.
๐ Example 5: Nested Loops with Conditions
for i in range(5):
for j in range(i + 1):
print("*", end=" ")
print()
Output:
*
* *
* * *
* * * *
* * * * *
This prints a right-angled triangle of stars.
โ ๏ธ Common Mistakes in Nested Loops
- Indentation Errors โ Proper indentation is critical in Python.
- Infinite Loops โ Especially when using nested
while
loops. - Unnecessary Complexity โ Sometimes nesting can be avoided.
- Mixing Variables โ Be careful not to confuse loop variables.
- Overusing Loops โ Nested loops can be inefficient for large datasets.
๐ก Best Practices
- Use descriptive variable names (e.g.,
row
,col
,i
,j
) - Keep loop depth to 2 or 3 levels max
- Consider breaking complex logic into functions
- Use
break
andcontinue
wisely - Profile and optimize loops in performance-sensitive code
โ Summary
Nested loops are a powerful way to handle repetitive, multi-dimensional, or structured tasks in Python. Whether youโre printing patterns, processing tables, or building more complex applications, understanding how and when to use nested loops is essential.
Although powerful, nested loops must be used carefully to avoid unnecessary complexity and performance issues. Practice with real examples, and soon youโll be using nested loops like a pro.
Would you like exercises with solutions or visual diagrams to help understand nested loops better? Iโd be happy to assist!