Articles → Numpy → Copy Array By Value And Reference In Numpy

Copy Array By Value And Reference In Numpy






Copy By Reference






 import numpy as np

arr = np.arange(0,10)

# Copy by reference
arr_ref = arr

# Printing array
print("Arr:", arr, ",  arr_ref:", arr_ref)

# Change in value of arr
arr[:] = 20

# Printing array
print("Arr:", arr, ",  arr_ref:", arr_ref)




  1. We have 2 arrays i.e. arr and arr_ref.
  2. The reference of arr is copied to arr_ref.
  3. Change in value of arr is also reflected in arr_ref..


Picture showing the output of copy array by reference in NumPy

Click to Enlarge


Copy By Value






 import numpy as np

arr = np.arange(0,10)

# Copy by values
arr_ref = arr.copy()

# Printing array
print("Arr:", arr, ",  arr_ref:", arr_ref)

# Change in value of arr
arr[:] = 20

# Printing array
print("Arr:", arr, ",  arr_ref:", arr_ref)




Picture showing the output of copy array by value in NumPy

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, March 28, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250