** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
list_copy
x = [1, 2, 3, 4, 5]
y = x
y[0] = 100
print('x = ', x)
print('y = ', y)
result
x = [100, 2, 3, 4, 5]
y = [100, 2, 3, 4, 5]
Even though I just messed with x
, the change extends to y
.
list_copy
x = [1, 2, 3, 4, 5]
y = x.copy()
y[0] = 100
print('x = ', x)
print('y = ', y)
result
x = [1, 2, 3, 4, 5]
y = [100, 2, 3, 4, 5]
By using x.copy ()
instead of x
,
You can substitute "a copy of x
"in y
instead of " x
itself ".
id_different
X = 20
Y = X
Y = 5
print('X = ', X)
print('Y = ', Y)
print('id of X =', id(X))
print('id of Y =', id(Y))
result
X = 20
Y = 5
id of X = 4364961520
id of Y = 4364961040
If you try to do the same with numerical values instead of lists, rewriting Y
will not affect X
.
If you look at the ids of X
and Y
using ʻid ()`, you can see that they are different ids.
id_same
X = ['a', 'b']
Y = X
Y[0] = 'p'
print('X = ', X)
print('Y = ', Y)
print('id of X =', id(X))
print('id of Y =', id(Y))
result
X = ['p', 'b']
Y = ['p', 'b']
id of X = 4450177504
id of Y = 4450177504
In the list, rewriting Y
also affects X
.
In this case, if you look at the id, you can see that both X
and Y
point to the same id.
id_same
X = ['a', 'b']
Y = X.copy()
Y[0] = 'p'
print('X = ', X)
print('Y = ', Y)
print('id of X =', id(X))
print('id of Y =', id(Y))
result
X = ['a', 'b']
Y = ['p', 'b']
id of X = 4359291360
id of Y = 4359293920
If avoided by .copy ()
You can see that the ids of X
and Y
are different.
Recommended Posts