Lecture focus: 2-D list processing
Course: COMP101 Introduction to Programming
Year: 2024-25
Lecture: 27
Function Definition: def list_init(data, num_rows, num_cols)
def list_init(data, num_rows, num_cols)
Parameters:
data: Value to fill the list
data
num_rows: Number of rows in the list
num_rows
num_cols: Number of columns in the list
num_cols
List Comprehension:
Creates a 2-D list initialized with 'data'
Syntax: return [[data for i in range(num_rows)] for j in range(num_cols)]
return [[data for i in range(num_rows)] for j in range(num_cols)]
Example Use in main() Function:
Call to function: unity_matrix = list_init(1, 4, 4)
unity_matrix = list_init(1, 4, 4)
Output:
print(unity_matrix)
Result:
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
Creates a unity matrix (4x4) filled with 1's.
Import random: Enables random number generation
Matrix Definition:
row = 3, col = 3
Initializing a 3x3 matrix with zeros:
list_3x3 = [[0,0,0],[0,0,0],[0,0,0]]
Randomization Loop:
Uses nested loops to fill the matrix
Code Explanation:
for r in range(row):
for c in range(col):
list_3x3[r][c] = random.randint(1, 4)
Example Output:
Example of a possible output:
[[2, 4, 4], [1, 2, 3], [3, 4, 1]]
Randomly fills a 3x3 list with integers between 1 to 4.
Initialization:
sum = 0
Example 2-D list: list_2x3 = [[1,2,3],[4,5]]
list_2x3 = [[1,2,3],[4,5]]
Nested Loop for Summation:
for row in list_2x3:
for col in row:
Adds each element to sum
sum
Code Example:
`print(