[Python] Why does this code for initializing a list of lists apparently link the lists...

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I intend to initialize a list of list with length of n.

    x = [[]] * n


    However, this somehow links the lists together.

    >>> x = [[]] * 3
    >>> x[1].append(0)
    >>> x
    [[0], [0], [0]]


    I expect to have something like:

    [[], [0], []]


    Any ideas?

    Continue reading...

Compartilhe esta Página