Working with python 3 arrays

The question is why when I create an array like this:

x = [[]]*3 

And then I'll add the element via the append method. For example so:

x[0].append(1)

The result is an array like this:

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

But, if I set this array initially in this form:

x=[[],[],[]]

Then using the same append method, as I indicated above, I will get this array:

[[1],[],[]]

Why is this happening ?

Author: MaxU, 2018-05-16

2 answers

In this case, the list is divided into 3 elements, and each element has a link to the same list.

x = [[]] * 3

Therefore, the expression x[0].append(1) has the result: [[1],[1],[1]]

If you want to check my statement, run the code print([hex(id(i)) for i in x]) and see that the id objects in the list are the same, i.e. they are the same object.

With this in mind, to create a list of lists, use the following code:

x = [[] for _ in range(3)]
x[0].append(1)
print(x)  # [[1], [], []]

I think this list creation code (x = [[]] * 3) is deployed in this form design:

value = []
number = 3
x = [value for _ in range(number)]

x[0].append(1)
print(x)

Therefore, the use of mutable types, such as lists, in such a syntactic construct is not recommended. Use simple immutable types such as strings, numbers, boolean values, etc.

For example:

x = [9] * 3
x[0] = 1
print(x)  # [1, 9, 9]
 5
Author: gil9red, 2018-05-16 08:33:48

Good afternoon. In the first case, you create an array consisting of 3 elements, each of which refers to the same object (they are copies). Therefore, by changing any of the array elements, you change the object to which they refer. In the second case, all the elements are different objects.

 0
Author: Denladon, 2018-05-16 08:20:16