Lecture-26 2d List_Output 2024-25

Lecture Overview

  • Course: COMP101 Introduction to Programming 2023-24

Page 1

  • Lecture Topic: 2-D List Output Numbers

  • Content: Basic understanding of 2-D lists

Page 2: Nested For Loops

  • Example Code:

    list_3x4 = [ [1,2,3,4], [5,6], [7,8,9] ]
    for row in range(len(list_3x4)):
    for column in range(len(list_3x4[row])):
    print(list_3x4[row][column], end=" ")
    print()
  • Output Format: Creates a structured output resembling a 2-D list:

    • Result:

      1 2 3 4 5 6 7 8 9

  • Explanation:

    • end = " " helps it print on the same line.

    • print() starts a new line after each row has been printed.

    • Indentation and loop structure are crucial to avoid misalignment in outputs.

  • Outer and Inner Loops:

    • Outer loop iterates through row indices.

    • Inner loop iterates through column indices.

Page 3: Similar Methods for Output

  • Alternative Code Examples:

    list_3x4 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]
    for row in list_3x4:
    for element in row:
    print(element, end = " ")
    print()
  • Output Explanation: Same output achieved through different iteration techniques.

  • Key Concept: Different structures still utilize the nested for loop.

Page 4: Another Output Example

  • Code Snippet:

    num_list = [ [1,2,3], [4,5,6], [7,8,9] ]
    for row in num_list:
    for column in row:
    print(column, end = " ")
    print()
  • Details:

    • Use either single or double quotes for string definitions.

    • A space between quotes (" ") creates spacing between numbers in each row.

    • Pay attention to the indentation of the final print statement for formatting.

Page 5: Accessing Rows and Columns

  • Example Accessing Code:

    list_out = [ [1,2,3], [4,5,6], [7,8,9] ]
    print(list_out[1]) # Output: [4, 5, 6]
    print(list_out[1][2]) # Output: 6
    print(len(list_out[2])) # Output: 3
  • Explanation:

    • Shows how to access individual rows and elements based on zero-based indexing.

    • Discusses the importance of remembering that indices start from 0.

Page 6: Types of Lists

  • Definitions:

    • Dense List:

      • Contains elements mostly or entirely with non-zero values.

      • Example: dense_list = [ [1,2,3], [4,5,6], [7,8,9] ]

    • Sparse List:

      • Contains many zero values amidst some non-zero elements.

      • Example: sparse_list = [ [1,0,3], [0,0,6], [7,0,0] ]

Page 7: Creating a 4x4 Array

  • Code for 4x4 Diagonal Matrix:

    list_diag_4x4 = [[0 for row in range(4)] for col in range(4)]
    for i in range(4):
    list_diag_4x4[i][i] = 1
  • Output Display:

    • Prints:

      1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1

    • Methodology: Follows three steps:

      1. Creating the list.

      2. Populating the diagonal.

      3. Outputting the list.

robot