Nested Lists and Nested Loops
In programming, nested
refers to one structure being contained within another structure.
For example, when a list contains another list or when a loop contains another loop, it is considered nested.
# A nested list containing the list [2, 3]
nested = [1, [2, 3], 4]
Nested lists are often used to represent matrices
, tables
, and multidimensional data structures
.
# 3x3 matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Nested Loops
Nested loops refer to a loop within another loop.
When a for loop contains another for loop, it is commonly called a nested for loop
.
In the nested for loop example below, the outer loop for row in matrix:
iterates over the rows of the list, while the inner loop for item in row:
iterates over the elements in each row.
# Print elements in a 3x3 matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Iterate over rows
for row in matrix:
# Iterate over elements in the row
for item in row:
print(item)
# Outputs 1, 2, 3, 4, 5, 6, 7, 8, 9 on separate lines
Nested loops are useful for iterating through data structures with two or more dimensions, such as multidimensional arrays.
Additionally, loops can be nested multiple times to form 3-level, 4-level nested loops, and so on.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.