For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
In Python, a nested for loop means putting one for loop inside another. This lets you repeat a block of code multiple times, especially useful for working with things like tables or grids. Nested loops in python are a key concept for handling iterative tasks.
This tutorial will teach you everything about nested for loops in Python, with clear explanations and practical nested for loop in python examples.
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
This nested for loop in python example will illustrate the key concepts clearly.
Consider the task of printing a multiplication table. Nested loops are perfectly suited for this.
for i in range(1, 4): # Outer loop: iterates from 1 to 3 (inclusive)
for j in range(1, 4): # Inner loop: iterates from 1 to 3 (inclusive) for each value of i
product = i * j # Calculate the product of i and j
print(f"{i} * {j} = {product}", end="\t") # Print the multiplication expression and result
print() # Print a newline character after each row is complete
Output:
1 * 1 = 1 1 * 2 = 2 1 * 3 = 32 * 1 = 2 2 * 2 = 4 2 * 3 = 63 * 1 = 3 3 * 2 = 6 3 * 3 = 9
Explanation:
This nested for loop in python example shows how different ranges affect the output.
Let's create a right-angled triangle pattern:
rows = 5 # Define the number of rows for the pattern
for i in range(rows): # Outer loop: iterates through each row
for j in range(i + 1): # Inner loop: iterates from from 0 to the current row number
print("*", end=" ") # Print an asterisk and a space
print() # Print a newline after each row
Output:
** ** * ** * * ** * * * *
Explanation:
Printing a multiplication table is a classic example that clearly demonstrates the use of nested loops in Python.
Let's generate a multiplication table up to a specified size:
size = 10 # Set the size of the table
print("Multiplication Table:") # Print the table header
# Print the header row
print(" |", end="") # Print a separator for the header row
for i in range(1, size + 1): # Iterate through the numbers for the header row
print(f"{i:3}", end="") # Print the number with width 3 for alignment
print() # Print a new line
print("-" * (4 * size + 3)) # Print a separator line
for i in range(1, size + 1): # Outer loop: iterates through rows
print(f"{i:2} |", end="") # Print the row header with a separator
for j in range(1, size + 1): # Inner loop: iterates through columns
product = i * j # Calculate the product # Calculate the product
print(f"{product:3}", end="") # Print the product with width 3 for alignment
print() # Print a newline after each row # Move to the next line
Output:
Multiplication Table: | 1 2 3 4 5--------------------- 1 | 1 2 3 4 5 2 | 2 4 6 8 10 3 | 3 6 9 12 15 4 | 4 8 12 16 20 5 | 5 10 15 20 25
Explanation:
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
A break statement only terminates the innermost loop in which it is placed. The outer loop continues to execute.
Let's illustrate this with an example where we search for a specific value in a 2D list and stop the search once the value is found:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
] # Create a 3x3 matrix
target = 5 # Set the value to find
found = False # Initialize a flag
for i in range(len(matrix)): # Outer loop: iterates through rows
for j in range(len(matrix[i])): # Inner loop: iterates through elements in the current row
if matrix[i][j] == target: # Check if the target is found
found = True # Set the flag
print(f"Found {target} at row {i}, column {j}") # Print the position
break # Exit the inner loop once the target is found # Exit the inner loop
if found: # Check if the target was found
break # Exit the outer loop
if not found: # If the target wasn't found after checking all the elements
print(f"{target} not found in the matrix") # Print a message indicating that the target is not found
Output:
Found 5 at row 1, column 1
Explanation:
Let's consider another scenario where we want to find the first row that contains a specific number:
matrix = [
[1, 2, 3],
[4, 7, 6],
[7, 8, 9]
] # create matrix
target = 7 # set the target
for i in range(len(matrix)): # loop through rows
for j in range(len(matrix[i])): # loop through elements in the row
if matrix[i][j] == target: # check if element is equal to target
print(f"Found {target} in row {i}") # print row index
break # break inner loop
else: # This else belongs to the outer loop
continue # Only continue if inner loop did NOT break
break # break outer loop
Output
Found 7 in row 1
Explanation:
When continue is executed in the inner loop, the remaining statements in that inner loop's current iteration are skipped, and the inner loop proceeds to its next iteration. The outer loop is unaffected.
Let's consider an example where we want to print pairs of numbers, but skip pairs where the second number is greater than the first:
for i in range(1, 5): # Outer loop: iterates from 1 to 4
for j in range(1, 5): # Inner loop: iterates from 1 to 4 for each i
if j > i: # Check if j is greater than i # Check if inner loop variable is greater than outer loop variable
continue # Skip the rest of the inner loop iteration if j > i # Skip to the next inner loop iteration
print(f"({i}, {j})", end=" ") # Print the pair
print() # Move to the next line
Output:
(1, 1)(2, 1) (2, 2)(3, 1) (3, 2) (3, 3)(4, 1) (4, 2) (4, 3) (4, 4)
Explanation:
Also Read: Python Break, Continue & Pass Statements [With Examples]
List comprehensions in Python provide a concise way to create lists. They can also be used to simulate nested loops in a single line, offering a more compact syntax for certain operations.
This nested for loop in python example shows how to use list comprehensions to achieve the effect of nested loops.
The general syntax for a nested list comprehension is:
[expression for outer_loop_variable in outer_sequence for inner_loop_variable in inner_sequence]
Let's start by creating a matrix (a list of lists) using a nested list comprehension:
rows = 3 # Set number of rows
cols = 4 # Set number of columns
matrix = [[0 for j in range(cols)] for i in range(rows)] # Create a 3x4 matrix filled with zeros
print(matrix) # Print the matrix
Output:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Explanation:
Let's look at another example where we create coordinate pairs:
coordinates = [(x, y) for x in range(1, 4) for y in range(1, 4)] # Create coordinate pairs (x, y) where x and y are from 1 to 3
print(coordinates) # Print the coordinates
Output:
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
Explanation:
Now, let's combine this with a conditional check, similar to using continue in a traditional nested loop.
We'll create coordinate pairs, but exclude cases where x equals y:
coordinates_filtered = [(x, y) for x in range(1, 4) for y in range(1, 4) if x != y] # Create pairs where x is not equal to y
print(coordinates_filtered) # print the filtered coordinates
Output:
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
Explanation:
A. A nested for loop in Python is a for loop placed inside another for loop. It allows you to execute a block of code multiple times, especially useful for iterating over multi-dimensional data.
A. You should use nested loops in Python when you need to iterate over items within items, such as rows and columns in a table, elements in a matrix, or characters in a list of strings. These nested loops in python examples are common.
A. The outer loop executes first. For each iteration of the outer loop, the inner loop completes all its iterations. This is a crucial aspect of how nested loops in python function.
A. Printing a multiplication table is a classic nested for loop in python example. The outer loop handles rows, and the inner loop handles columns.
A. The break statement only terminates the innermost loop in which it is placed. The outer loop continues to execute unless there is a break statement outside the inner loop as well.
A. The continue statement skips the rest of the current iteration of the innermost loop and proceeds to the next iteration of that inner loop. The outer loop is unaffected.
A. Yes, you can use different ranges. This allows you to create various patterns and control the iterations of each loop independently as shown in many nested loops in python examples.
A. Yes, you can nest while loops inside for loops and for loops inside while loops. The same principles of execution apply.
A. You can use nested list comprehensions, where one list comprehension is nested inside another. This provides a concise way to create multi-dimensional lists.
A. You can add an if condition to the inner part of a nested list comprehension to filter elements, effectively simulating the behavior of a continue statement in traditional nested loops. This is a compact way to perform nested loops in python.
A. While powerful, nested loops can become inefficient for very large datasets or deeply nested structures. In those cases, consider alternative approaches like vectorization with NumPy or different data structures. However, for many common tasks, nested loops in python offer a clear and effective solution, as illustrated by many nested for loop in python example.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.