Are numpy arrays passed by reference?

In this tutorial, we will learn are numpy arrays passed by reference or how can I pass numpy arrays as reference? By Pranit Sharma Last updated : September 16, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Basically, in python, all the variable names are passed by reference. Suppose that we are passing an array into a function where we are subtracting some values from the original array.

Passing numpy arrays by reference

When Python evaluates an assignment, the right-hand side is evaluated before the left-hand side. Any operation on an array creates a new array; it does not modify the arr in-place.

Any operation makes the local variable a reference to the new array. It does not modify the value originally referenced by arr which was passed to function.

Let us understand with the help of an example,

Python code to pass numpy arrays by reference

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([3, 4, 5])

# Display original array
print("Original array:\n",arr,"\n")

# Defining a function
def fun(a):
    a = a - 3
    return a

# Calling the function
res = fun(arr)

# Display the result
print("Result:\n",res)

Output

The output of the above program is:

Example: Are numpy arrays passed by reference?

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.