[Python] List manipulation in Python (matrix as a list of list) [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I want to define a function called "create_matrix" that first creates an l1+1 by l2+1 matrix of zeros (implemented as a list of list; NOT numpy). Next, the function should set the first row to be [0, 1, 2, ..., l2], and the first column to be [0, 1, 2, ..., l1].

    However, running the function create_matrix(7,8) returns the following matrix (see picture), which is not expected. Could you please tell me why?

    [​IMG]

    def create_matrix(l1, l2):
    matrix = [[0]*(l2+1)]*(l1+1)
    matrix[0] = [i for i in range(0,l1+2)]
    counter = 0
    for inner_list in matrix:
    inner_list[0] = counter
    counter += 1
    return matrix
    create_matrix(7,8)

    Continue reading...

Compartilhe esta Página