Copying Lists in Python

make sure you don’t fall into the trap of copying pointers in Python:

 import numpy as np a = np.zeros(2) print("a = ", a) b = np.zeros(2) print("b = ", b) b = a # this assignment is simply a pointer copy - b points to the same data pointed to by a a[0]=33.33 # this will actually change b as well print("b = a results in a shallow copy:") print("a = ", a) print("b = ", b) # to avoid this, do a deep copy: print("To create a data copy, use b = a.copy() or b = list(a):") a = np.zeros(2) print("a = ", a) b = np.zeros(2) print("b = ", b) print("b = a.copy or b = list(a) results in a data copy:") b = a.copy() # this assignment will make a copy of the data a[0]=33.33 # this will actually change b as well print("a = ", a) print("b = ",b)