[PYTHON] Be careful when adding an array to an array

I did not know that...

JavaScript

const data_list = [];
let data = [];
data[0] = 0;
data[1] = 1;
data[2] = 2;
data_list.push(data);
console.log('data:', data); // [0, 1, 2]
console.log('data_list:', data_list); // [[0, 1, 2]]

// data = [];
data[0] = 3;
data[1] = 4;
data[2] = 5;
data_list.push(data);
console.log('data:', data); // [3, 4, 5]
console.log('data_list:', data_list); // [[3, 4, 5], [3, 4, 5]]

Python

data_list = []
data = [0, 0, 0]
data[0] = 0
data[1] = 1
data[2] = 2
data_list.append(data)
print ('data: ', data) # [0, 1, 2]
print ('data_list: ', data_list) # [[0, 1, 2]]

# data = [0, 0, 0]
data[0] = 3
data[1] = 4
data[2] = 5
data_list.append(data)
print ('data: ', data) # [3, 4, 5]
print ('data_list: ', data_list) # [[3, 4, 5], [3, 4, 5]]

If you think about it, it seems obvious, but since the addresses of the array added the first time and the array added the second time are the same, they are the same value by the time they are referenced. To get the expected result [[0, 1, 2], [3, 4, 5]], you need to initialize the array at the right time.

Do not overwrite the contents of the array by stopping thinking. Even if you are using a scripting language, be aware of memory when dealing with arrays.

By the way, I buried the data that was supposed to be collected in the experiment by this method in the darkness (crying) (stupid)

Recommended Posts

Be careful when adding an array to an array
Be careful when assigning Series as a column to pandas.DataFrame
Settings when adding an HDD in Linux
Be careful when running CakePHP3 with PHP7.2
[Python memo] Be careful when creating a two-dimensional array (list of lists)
Be careful of the type when making an image mask with Numpy
Add rows to an empty array with numpy
I want to be an OREMO with setParam!
Be careful when working with gzip-compressed text files
Be careful when differentiating the eigenvectors of a matrix
Be careful when reading data with pandas (specify dtype)
Convert dict to array
Create a 2D array by adding a row to the end of an empty array with numpy
How to convert an array to a dictionary with Python [Application]
How to swap elements in an array in Python, and how to reverse an array.
Record of actions to be taken when google_image_download cannot be used
Garbled characters when printing an array containing a string containing utf-8
Set Tomcat to restart automatically when it raises an OutOfMemoryError
What to do when an error occurs with import _ssl
How doi may be useful when asking how to write code?
I wanted to calculate an array with Sympy's subs method
(Note) Points to be addicted to when installing Scilab on ArchLinux
[Introduction to Udemy Python3 + Application] 51. Be careful with default arguments
How to get rid of the "Tags must be an array of hashes." Error in the qiita api