List of objects that change when the original object changes.

In Python, if I write:

a = [1]
b = 3 * [a]
a.append(2)
print a, b

Then the conclusion:

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

However, when I write:

a = [1]
b = 3 * a # notice the missing brackets here 
a.append(2)
print a, b

It turns out:

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

What's going on here?

+4
source share
2 answers

In the first example, consider what Python does for this statement:

b = 3 * [a]

This will:

b = [[a], [a], [a]]

Thus, the change awill be reflected in b, because it bconsists of objects a.

However, in the second example, you do the following:

b = 3 * a

Creates a copy of the list aand is equivalent to:

b = [1, 1, 1]

Thus, when adding to athis time, nothing has changed.

+3
source

, , b = 3 * [a], a . , , a, b.

b = 3 * a list, a.

Python , .:)

+1

Source: https://habr.com/ru/post/1678422/


All Articles