Precautions when creating a two-dimensional array with all the same values

I was addicted to a two-dimensional array

When creating a two-dimensional array in which the values of all elements are 0 and counting up each element, if you specify a column with a certain row and update the value, the same column of all rows will be updated. I've done it, so I'll keep it as a memorandum so that I won't get hooked on the same place in the future.

How to make a 2D array when you get hooked

By doing the following, a two-dimensional array of 4 rows and 10 columns can be created.

array2D = [[0] * 10] * 4

For example, if you update the values in the 3rd row and 5th column as shown below, ...

array2D[2][4] += 1

The fifth column of every row has been updated.

[[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]

If you make it like the above, the array of each row will be the same.

How to make each row as a separate array

You can do this.

array2D = [[0] * 10, [0] * 10, [0] * 10, [0] * 10]

However, it's not smart, so I think it's better to make it like this.

array2D = [[0] * 10 for _ in range(4)]

Recommended Posts

Precautions when creating a two-dimensional array with all the same values
[Python] Precautions when finding the maximum and minimum values in a numpy array with a small number of elements
Precautions when creating a Python generator
[Python memo] Be careful when creating a two-dimensional array (list of lists)
A memo when creating a python environment with miniconda
Precautions when installing a hierarchical include directory with waf
Problems when creating a csv-json conversion tool with python
Current directory when creating a new one with Jupyter
Creating a list when the nomenclature is a fixed time
When a local variable with the same name as a global variable is defined in the function
The first step to creating a serverless application with Zappa
Automatically rename a node with the same name found while working
How to get all the possible values in a regular expression
Precautions when using a list or dictionary as the default argument
A note I was addicted to when creating a table with SQLAlchemy
A memo when creating an environment that can be debugged with Lambda @ Edge for the time being
Precautions when inheriting the DatasetMixin class
Creating a decision tree with scikit-learn
Precautions when installing tensorflow with anaconda
Creating a Flask server with Docker
Precautions when using the urllib.parse.quote function
Creating a simple app with flask
When creating a matrix in a list
Precautions when using six with Python 2.5
Deb package development with Git: (Part 1) Creating a stray package with the minimum configuration
I made a function to see the movement of a two-dimensional array (Python)