Lecture-27 2d List_Operations 2024-25

COMP101 Introduction to Programming 2024-25 Lecture-27

2-D List Processing

Page 1

  • Lecture focus: 2-D list processing

  • Course: COMP101 Introduction to Programming

  • Year: 2024-25

  • Lecture: 27

Page 2

Function for List Initialization

  • Function Definition: def list_init(data, num_rows, num_cols)

    • Parameters:

      • data: Value to fill the list

      • num_rows: Number of rows in the list

      • num_cols: Number of columns in the list

    • 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)]

  • Example Use in main() Function:

    • Call to function: 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]]

Summary

  • Creates a unity matrix (4x4) filled with 1's.

Page 3

Random Initialization of a 3x3 List

  • 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]]

Summary

  • Randomly fills a 3x3 list with integers between 1 to 4.

Page 4

Summing Values in a 2-D List

  • Initialization:

    • sum = 0

    • Example 2-D list: 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

  • Code Example:

    • `print(

robot