Course Content
Python Loops Tutorial
Python Loops Tutorial
Nested for Loop 2 (del)
Let's delve into the world of matrices!
With the aid of a nested loop, we can manipulate matrices.
In mathematics, a matrix is a rectangular array or table of numbers, symbols, or expressions organized in rows and columns. It's used to represent a mathematical object or a characteristic of such an object.
In Python, a matrix is a data structure composed of nested lists.
The outer loop will handle the matrix's rows, while the inner loop will manage the columns, or vice versa.
Note
len(matrix)
signifies the number of rows.len(matrix[i])
represents the count of elements in a row (equivalent to the number of columns). Or vice versa.
Examine the code below:
matrix = [ [1, 2, 4, 29], [3, 4, 6, 1] ] # Printing every element in the matrix # Outer loop to work with the number of rows for i in range(len(matrix)): # Inner loop to work with the number of element in the row for j in range(len(matrix[i])): print(matrix[i][j], end = ' ') print('')
How does this code work?
Swipe to show code editor
You must calculate the sum of all elements within the matrix.
- Initialize
counter = 0
. - Configure the outer
for
loop to iterate through the number of rows in the matrix. - Configure the inner
for
loop to iterate through the number of elements in each row of the matrix. - Accumulate the sum using the
counter
variable. - Display the value stored in the
counter
.
Thanks for your feedback!
Nested for Loop 2 (del)
Let's delve into the world of matrices!
With the aid of a nested loop, we can manipulate matrices.
In mathematics, a matrix is a rectangular array or table of numbers, symbols, or expressions organized in rows and columns. It's used to represent a mathematical object or a characteristic of such an object.
In Python, a matrix is a data structure composed of nested lists.
The outer loop will handle the matrix's rows, while the inner loop will manage the columns, or vice versa.
Note
len(matrix)
signifies the number of rows.len(matrix[i])
represents the count of elements in a row (equivalent to the number of columns). Or vice versa.
Examine the code below:
matrix = [ [1, 2, 4, 29], [3, 4, 6, 1] ] # Printing every element in the matrix # Outer loop to work with the number of rows for i in range(len(matrix)): # Inner loop to work with the number of element in the row for j in range(len(matrix[i])): print(matrix[i][j], end = ' ') print('')
How does this code work?
Swipe to show code editor
You must calculate the sum of all elements within the matrix.
- Initialize
counter = 0
. - Configure the outer
for
loop to iterate through the number of rows in the matrix. - Configure the inner
for
loop to iterate through the number of elements in each row of the matrix. - Accumulate the sum using the
counter
variable. - Display the value stored in the
counter
.
Thanks for your feedback!