Python: Nested Loops
Python Nested Loops
1 Overview
📘 Nested loops in Python
A nested loop in Python refers to a construction where one loop (the inner loop) is placed inside the body of another loop (the outer loop). For each iteration of the outer loop, the inner loop runs all its iterations from beginning to end before the outer loop proceeds to its next iteration.
2 Key Concepts
- The outer loop acts as the main controller, and the inner loop completes its cycle entirely within each cycle of the outer loop.
- Any type of loop (for or while) can be nested within another, with no formal limit on nesting depth.
- Nested loops are widely used for tasks involving multi-dimensional or hierarchical data, such as traversing matrices, grids, or groups within groups.
- The total number of iterations in a nested loop equals the product of the iteration counts of the inner and outer loops.
- The design can be extended to multiple levels, creating deep layers of nested logic as needed.
- Although powerful, nested loops may introduce performance or readability concerns, especially when deeply nested or used with large datasets.
- This structure enables efficient handling of repetitive actions that require layered processing, like iterating over two-dimensional arrays or generating combinations.
3 Nested Loops
- We can nest multiple loops inside one another:
- What does this print?
5 1
—
6 0
6 1
Outside the loop
breakonly “breaks” the last (inner) loop. If this one is nested, the outer loops are not affected.What does the following code print?
4 With list comprehension
5 Matrices
Also known as matrices.
Example:
Normally visualized as rows and columns:
| # | Col 1 | Col 2 |
|---|---|---|
| 0 | 3 | 4 |
| 1 | 1 | 5 |
| 2 | 2 | 2 |
6 Accessing a row
- For accessing a specific row, just use indexing for accessing the matrix element.
[1, 5]
7 Accessing an element
- For accessing a specific element in the matrix, just use “double” indexing.
- The first index returns a row (which is a list), as seen before. We then access an element of that list with the second index.
5
2
8 Iterating row-wise
We can iterate through each element in the list, which corresponds to each row.
Iterate through the matrix row-wise:
[1, 5]
[2, 2]
- When we want to keep the row index:
1, [1, 5]
2, [2, 2]
Another option (more common in other languages).
The length of the matrix is 3, as it contains 3 elements (rows).
1, [1, 5]
2, [2, 2]
- For iterating through each element we need a nested loop:
- Example, in a less pythonic way.
9 Iterating column-wise
- For iterating through each element column-wise:
- For iterating column-wise things get a bit more complex.
[4, 5, 2]
10 Unpacking in loops
- We can unpack elements in loops row-wise.
6
4
- As many as we want, as long as each row contains the same number of elements.
1 5 8 7
2 2 9 6