This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Create a copy and not a reference of a NumPy array
(1 answer)
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
Closed 7 years ago.
If I run the following code in Python 2.7, I get [2., 2., 2.] printed for both a and b. Why does b change together with a? Many thanks!
def test_f(x):
a = np.zeros(3)
b = a
for i in range(3):
a[i] += x
print a
print b
return 0
test_f(2)
Because b and a are referring to the same list in memory. b = a does not create a new copy of a.
Try this and see the difference:
def test_f(x):
a = np.zeros(3)
b = a.copy()
for i in range(3):
a[i] += x
print a
print b
return 0
test_f(2)
b = a.copy() will create a new copy that exactly resembles the elements of a, whereas b=a just creates a new reference to the exisiting list.
numpy will use a pointer to copy unless you tell it otherwise:
import numpy as np
def test_f(x):
a = np.zeros(3)
b = np.copy(a)
for i in range(3):
a[i] += x
print a
print b
return 0
test_f(2)
[ 2. 2. 2.]
[ 0. 0. 0.]
Related
This question already has answers here:
Changing one list unexpectedly changes another, too [duplicate]
(5 answers)
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 8 months ago.
could someone explain why this thing exists and how to counteract it
a = [1, 2, 3]
b = a
b[1] = 0
print(a)
a = [1, 0, 3]
Its bugging me, because, when I use this with int, then it acts normally.
a = 1
b = a
b +=1
print(a)
a = 1
It`s really messing with some of my code
Thanks in advance
By doing b = a you are having both point to the same spot in memory. Thus, changes to one will reflect in the other.
A simple fix to copy an array without them being connected:
b = a[:]
b = a is making b a reference to the same list as a. Use
b = a.copy()
to make a separate list.
This question already has answers here:
If two variables point to the same object, why doesn't reassigning one variable affect the other?
(4 answers)
Are Python variables pointers? Or else, what are they?
(9 answers)
Closed 2 years ago.
I understand that given this code
a = [1,2,3]
b = [4,5,6]
c = a
and then by doing this
a[0] = 0
I wil change first positions of both a and c. Could somebody explain why this doesn't apply when I do this:
a = b
ie. why c doesn't become equal to b?
a = [1,2,3]
b = [4,5,6]
# a ────────> [1,2,3]
# b ────────> [4,5,6]
c = a # Changing 'c' to point at the list that 'a' points at
# c ─────┐
# a ─────┴──> [1,2,3]
# b ────────> [4,5,6]
a = b # Changing 'a' to point at the list that 'b' points at
# c ─────┐
# a ──┐ └──> [1,2,3]
# b ──┴─────> [4,5,6]
Because python interprets the line of code from the beginning of the code to the bottom line. Therefore, you have been assigned the b to a, after assigning a to c. The value of c is not changed until reassigning c.
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 2 years ago.
Why is my function 'increment' return different values for matrix that i create by other function and different for manual matrix?
n = 2
m = 3
indices = [[0,1],[1,1]]
def matrixpopulation(n,m):
row=[]
matrix=[]
row+=(0 for _ in range(0,m))
matrix+=(row for _ in range(0,n))
return matrix
def increment(indices,matrixa):
for v,k in indices:
for i in range(3):
matrixa[v][i]+=1
for i in range(2):
matrixa[i][k]+=1
return matrixa
matrixa=matrixpopulation(n,m)
filled_matrix=increment(indices,matrixa)
print(matrixpopulation(n,m))
print(filled_matrix)
manualmatrix=[[0,0,0],[0,0,0]]
print(manualmatrix)
print(increment(indices,manualmatrix))
matrix+=(row for _ in range(0,n))
When you make matrix here you actually add the reference to the same row n-times. When you modify some element in one 'row', all other rows are modified as well. For example:
a = [1, 2]
b = [a, a]
a[0] = 3
Check b now.
This question already has answers here:
Python variable assignment question
(6 answers)
Closed 6 years ago.
I am learning python and I have some question:
What is the difference between
a,b = 0,1
for x in range(100):
print(a)
a=b
b=a+b
and
a,b = 0,1
for x in range(100):
print(a)
a,b = b, a+b
First one gives bad result, but why?
Because you first set a = b, your new b will have the value of twice the old b. You overwrite a to early. A correct implementation should use a temporary variable t:
a,b = 0,1
for x in range(100):
print(a)
t=a
a=b
b=t+b
This is basically what you do by using sequence assignment.
In your original code you have:
a,b = 0,1
for x in range(100):
print(a)
a=b # a now is the old b
b=a+b # b is now twice the old a so b'=2*b instead of b'=a+b
So this would result in jumping by multiplying with two each time (after first loading in 1 into a the first step).
An equivalent problem is the swap of variables. If you want a to take the value of b and vice versa, you cannot write:
#wrong swap
a = b
b = a
Because you lose the value of a after the first assignment. You can use a temporary t:
t = a
a = b
b = t
or use sequence assignment in Python:
a,b = b,a
where a tuple t = (b,a) is first created, and then assigned to a,b.
This question already has answers here:
What is the difference between shallow copy, deepcopy and normal assignment operation?
(12 answers)
Closed 7 years ago.
a = [ 1, 2, [3,4] ]
b = list(a) # create a shallow copy of a
c = a
print (b is a) # False
print (c is a)
b.append(100) # append element to b
print (b)
print (a) # a is unchanged
print (c)
c.append(100) # append element to c
print (b) # b is unchanged
print (a)
print (c)
b[2][0] = -100 # modify an element inside b
print (b)
print (a) # a is changed
print (c)
c[2][0] = -200
print (b) # b is changed
print (a) # a is changed
print (c)
As a beginner in python, I'm not sure what is the meaning of shadow copy, why b.append cannot change a, why c.append cannot change b, why b[2][0] can change a, and why c[2][0] can change b. Thank you!
This is happening because shallow copy b contains references to the list [3,4].
So when you do b[2][0] = -100 then since b is having the reference of the nested list hence both a and b gets affected. If you had done deep copy the list [3,4] would be created again in memory and it will be pointed by b
Due to above reason c[2][0] also changes b since c is also pointing to the same list as a