Empty multidimensional array in python

A note of what I was addicted to when creating an empty multidimensional array

Creating an empty two-dimensional array

I wanted to create an empty 2D array in the script, so I created it with the following code.

hoge = [[]] * 5

Then, for some reason, I don't get the results I expected. For example,

>>> hoge = [[]] * 5
>>> for i in range(5):
        hoge[i].append(i)

When you check the contents of hoge like

>>> print hoge
[[0],[1],[2],[3],[4]]

I thought it would be

>>> print hoge
[[0,1,2,3,4],[1,2,3,4],[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]]

It has become like this. After all, the object duplicated with * seems to be only a reference to the original object, like the object created by the assignment with =. After all, to create an empty two-dimensional array,

[[] for i in range(5)]

I wonder if it's best to do it.

Recommended Posts

Empty multidimensional array in python
Python multidimensional array
Quicksort an array in Python 3
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
[Beginner] Python array
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
Python array basics
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
[Python] Combine all the elements in the array
flatten in python
Try implementing two stacks in one array in Python
Output in the form of a python array
Randomly select elements from list (array) in python
[Python] Manipulating elements in a list (array) [Sort]
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python