Home>

Two-dimensional list
l = [[]] * 5
Trying to add an element that is only on the first line, for example
l [0] .append (3)
Will add the element to every row
[[3], [3], [3], [3], [3]]
Why is it?

Error message

Corresponding source code What I tried Supplementary information (FW/tool version, etc.)
  • Answer # 1

    How do you make a multidimensional list?

    This is because duplicating a list with * does not make a copy, it just makes a reference to an existing object.

    You can check this with the code below.

    l = [0] * 3
    # All have the same id (= reference)
    print ([f'{id (e)}' for e in l])
    # ['140732214949632', '140732214949632', '140732214949632']

Related articles