Introduction to Python Nested Loops
In Python, a nested loop is a loop within a loop. It allows you to iterate over multiple levels of data structures, such as lists within lists or dictionaries within lists. Nested loops are useful when you need to perform repetitive tasks on each element of a nested data structure.
Syntax of Nested Loops
The syntax for a nested loop in Python is as follows:
for outer_loop_variable in outer_loop_sequence:
for inner_loop_variable in inner_loop_sequence:
# Code block to be executed
Example 1: Nested Loop with Lists
Let’s consider a scenario where you have a list of fruits, and each fruit has a list of colors associated with it. You want to print each fruit along with its colors.
fruits = ["apple", "banana", "orange"]
colors = [["red", "green"], ["yellow", "brown"], ["orange", "yellow"]]
for i in range(len(fruits)):
print("Fruit:", fruits[i])
for j in range(len(colors[i])):
print("Color:", colors[i][j])
The output of this code will be:
Fruit: apple
Color: red
Color: green
Fruit: banana
Color: yellow
Color: brown
Fruit: orange
Color: orange
Color: yellow
Example 2: Nested Loop with a Dictionary
Let’s say you have a dictionary that contains information about students and their subjects. You want to print each student along with their subjects.
students = {
"John": ["Math", "Science"],
"Sarah": ["English", "History"],
"Michael": ["Physics", "Chemistry"]
}
for student, subjects in students.items():
print("Student:", student)
for subject in subjects:
print("Subject:", subject)
The output of this code will be:
Student: John
Subject: Math
Subject: Science
Student: Sarah
Subject: English
Subject: History
Student: Michael
Subject: Physics
Subject: Chemistry
Advantages and Use Cases of Nested Loops
Nested loops provide flexibility and allow you to work with complex data structures. They are commonly used in scenarios such as:
- Processing multidimensional arrays or matrices
- Performing calculations on hierarchical data structures
- Generating combinations or permutations
- Searching and filtering data
Conclusion
Python nested loops are a powerful tool for iterating over complex data structures. They allow you to perform repetitive tasks on each element of a nested list, dictionary, or other data structures. By understanding the syntax and examples provided in this article, you can effectively use nested loops in your Python programs.