0

Hi I seem to having issues understanding of passing object by reference in Python. I understand example 1 output, but shouldn't example 2 behave in the similar way and not change the A matrix?

Example 1:

def reassign(list):
  list = [0, 1, 2]

list = [3]
reassign(list)
print(list)

Returns: [3]

Example 2:

import numpy as np

A = np.ones((4,4))

def xyz(A):
    for i in range(4):
        A[i,i] = 0    
    return None

x = xyz(A)
print(A)

# Returns

[[0. 1. 1. 1.]
 [1. 0. 1. 1.]
 [1. 1. 0. 1.]
 [1. 1. 1. 0.]]
anuragsodhi
  • 75
  • 1
  • 1
  • 8
  • Possible duplicate of [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) –  Dec 04 '18 at 03:49

1 Answers1

0

Passing by reference means that, when you pass a variable into the function, you don't pass the variable itself, you pass the pointer to the variable, which is copied from outside to inside the function. In Example 1, you pass list into the function, which is a pointer to a list that contains the elements [3]. But then, immediately after, you take that variable holding the pointer to the list, and put a new pointer in it, to a new list that contains the elements [0, 1, 2]. Note that you haven't changed the list you started with - you changed what the variable referring to it referred to. And when you get back out of the function, the variable you passed into the function (still a pointer to the first list) hasn't changed - it's still pointing to a list that contains the elements [3].

In Example 2, you pass A into xyz(). Whereas in Example 1 you did something along the lines of

A = something_else

here, you're doing

A[i] = something_else

This is an entirely different operation - instead of changing what the variable holding the list is pointing to, you're changing the list itself - by changing one of its elements. Instead of making A point to something else, you're changing the value that A points to by dereferencing it.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53