88014

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

ではないのですか？


CC BY-SA 4.0
2022-03-25T01:44:45.460
88013
2022-03-25T02:08:39.590
2022-03-25T01:55:12.137
51952
51952
question
python python3
PythonのListについての質問


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

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


CC BY-SA 4.0
2022-03-25T02:08:39.590
88014
2022-03-25T02:08:39.590
47127
88013
answer