Array Access by Reference or by Value in Python

Array Access by Reference or by Value in Python

Postby yiboj » Thu May 17, 2018 8:23 am

Array or matrix access and manipulation could be confusing for the beginner. The default python array access is by reference, and the copy routine has to be used if you need do a hard copy (copy value only). Please see the following code for the demonstration:

Code: Select all
>>> from pylab import *
>>> a = np.arange(1,10)
>>> print(a)
[1 2 3 4 5 6 7 8 9]
>>> ar = a  # assign by reference
>>> ar[0] = 10  # now change the first element value of array ar
>>> print(a)
[10  2  3  4  5  6  7  8  9]
>>>
>>> a = np.arange(1,10)  # re-initiate the array
>>> print(a)
[1 2 3 4 5 6 7 8 9]
>>> av = a.copy()  # hard copy
>>> av[0] = 10  # now change the first element value of array av
>>> print(a)
[1 2 3 4 5 6 7 8 9]
yiboj
 
Posts: 82
Joined: Mon Mar 30, 2015 11:22 am

Return to Data Recipes

cron