PythonのListについての質問

[code]

    x = [[0] * 3] * 3
    a = 1
    for i in range(3):
        for j in range(3):
            x[i][j] = a
            a += 1
    for i in x:
        print(i)
    
[/code]

の出力結果が

[code]

    [7, 8, 9]
    [7, 8, 9]
    [7, 8, 9]
    
[/code]

となる理由がわかりません。  
なぜ

[code]

    [1, 2, 3]
    [4, 5, 6]
    [7, 8, 9]
    
[/code]

ではないのですか？




リストの要素のアドレスが全て同じ(同一のインスタンス)、だからです。

[code]

    >>> x = [[0] * 3] * 3  # shallow copy
    >>> x
    [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    >>> [*map(id, x)]
    [140087188915840, 140087188915840, 140087188915840]
    
[/code]

別個のインスタンスを作成する場合は、例えば以下の様にします。

[code]

    >>> x = [[0] * 3 for _ in range(3)]
    >>> [*map(id, x)]
    [140087168176192, 140087168988480, 140087168028224]
    
[/code]

[code]

    x = [[0] * 3 for _ in range(3)]
    a = 1
    for i in range(3):
        for j in range(3):
            x[i][j] = a
            a += 1
    
    for i in x:
        print(i)
    
    #
    [1, 2, 3]
    [4, 5, 6]
    [7, 8, 9]
    
[/code]




リストの要素のアドレスが全て同じ(同一のインスタンス)、だからです。

[code]

    >>> x = [[0] * 3] * 3  # shallow copy
    >>> x
    [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    >>> [*map(id, x)]
    [140087188915840, 140087188915840, 140087188915840]
    
[/code]

別個のインスタンスを作成する場合は、例えば以下の様にします。

[code]

    >>> x = [[0] * 3 for _ in range(3)]
    >>> [*map(id, x)]
    [140087168176192, 140087168988480, 140087168028224]
    
[/code]

[code]

    x = [[0] * 3 for _ in range(3)]
    a = 1
    for i in range(3):
        for j in range(3):
            x[i][j] = a
            a += 1
    
    for i in x:
        print(i)
    
    #
    [1, 2, 3]
    [4, 5, 6]
    [7, 8, 9]
    
[/code]

