Guidelines

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.

Example of Nested List
# 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.

Example of Nested List
# 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.

Example of Nested Loop
# 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 very useful for iterating through data structures with two or more dimensions, such as processing multidimensional arrays.

Additionally, loops can be nested multiple times to form 3-level, 4-level nested loops, and so on.

Mission
0 / 1

What is the most appropriate word for the blank below?

Including another for loop inside a for loop is called a .
single for loop
nested for loop
while loop
if statement

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result