88014
```

    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)
    
```

の出力結果が

```

    [7, 8, 9]
    [7, 8, 9]
    [7, 8, 9]
    
```

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

```

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

ではないのですか？
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についての質問
リストの要素のアドレスが全て同じ(同一のインスタンス)、だからです。

```

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

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

```

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

```

    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]
    
```
CC BY-SA 4.0
2022-03-25T02:08:39.590
88014
2022-03-25T02:08:39.590
47127
88013
answer