Iterate Over a 2D List in Python
To iterate over a 2D list in Python, we typically use nested loops. The outer loop goes through each row (a sublist), while the inner loop iterates over each element within that row. Depending on the requirement, we can use different iteration techniques such as for
loops, list comprehension, and enumerate()
. Below are different ways to iterate over a 2D list with explanations.
Examples
1. Iterating Using Nested Loops
The most common way to iterate over a 2D list is by using nested for
loops. The outer loop retrieves each row, and the inner loop retrieves each element in that row.
# Defining a 2D list (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Iterating over the 2D list
for row in matrix:
for element in row:
print(element, end=" ")
print() # New line after each row
In this example:
- The
matrix
variable is a 2D list containing three sublists (rows). - The outer loop iterates through each row in
matrix
. - The inner loop iterates through each element in the current row and prints it.
- The
print()
statement at the end ensures each row appears on a new line.
Output:
1 2 3
4 5 6
7 8 9
2. Iterating Using Indexes
Instead of directly accessing elements, we can use range()
to iterate by index.
# Defining a 2D list
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
# Iterating using indexes
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i][j], end=" ")
print()
Explanation:
- The outer loop iterates using
i
, which represents the row index. - The inner loop iterates using
j
, which represents the column index. - The element is accessed using
matrix[i][j]
, and printed with a space separator.
Output:
10 20 30
40 50 60
70 80 90
3. Iterating Using enumerate()
Using enumerate()
, we can access both the index and value while iterating over a 2D list.
# Defining a 2D list
matrix = [
["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]
]
# Iterating using enumerate()
for i, row in enumerate(matrix):
for j, element in enumerate(row):
print(f"Element at ({i},{j}) is {element}")
Explanation:
- The outer loop uses
enumerate()
to get both the row indexi
and the row valuerow
. - The inner loop also uses
enumerate()
to get the column indexj
and the element value. - The formatted string
f"Element at ({i},{j}) is {element}"
prints the position and value.
Output:
Element at (0,0) is a
Element at (0,1) is b
Element at (0,2) is c
Element at (1,0) is d
Element at (1,1) is e
Element at (1,2) is f
Element at (2,0) is g
Element at (2,1) is h
Element at (2,2) is i
4. Using List Comprehension
List comprehension offers a concise way to iterate over a 2D list.
# Defining a 2D list
matrix = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]
# Using list comprehension to iterate and print
[print(element, end=" ") for row in matrix for element in row]
Explanation:
- The outer loop iterates over each row in
matrix
. - The inner loop iterates over each element in that row.
- Each element is printed using
print(element, end=" ")
.
Output:
1 4 7 2 5 8 3 6 9
Conclusion
We covered multiple ways to iterate over a 2D list in Python:
- Using nested loops for straightforward iteration.
- Using indexes with
range()
for precise control. - Using
enumerate()
to access both index and value. - Using list comprehension for a compact approach.