0

Why can I change a global numpy array from inside a function without using a explicit global reference to it?

import numpy as np
def test():
    a[0,0,0] = 34
    print(a)

a = np.zeros( (3, 2, 4), dtype=np.int)
test()
print(a)

both print() are equal to:

[[[34  0  0  0]
  [ 0  0  0  0]]

 [[ 0  0  0  0]
  [ 0  0  0  0]]

 [[ 0  0  0  0]
  [ 0  0  0  0]]]
[[[34  0  0  0]
  [ 0  0  0  0]]

 [[ 0  0  0  0]
  [ 0  0  0  0]]

 [[ 0  0  0  0]
  [ 0  0  0  0]]]

This contradicts what other thread here says.

juanfal
  • 11
  • 3
  • Objects aren't global or local. Variables are global or local. The array is the same array, with two variables referring to it. – user2357112 Feb 18 '19 at 23:30
  • 1
    There is no contradiction. You can access a global variable just fine without a global statement, but any assignment will default to a local variable unless you use the global statement. Here you are simply referencing a global variable and mutating the object being referenced by that variable – juanpa.arrivillaga Feb 18 '19 at 23:46
  • So, actually, objects can be local or global and, when created locally, they are freed after their scopes vanish, but if you refer to an existing global object without creating a new one, it changes the global object. So the key point here is knowing when each thing in Python is an object or not. – juanfal Feb 19 '19 at 18:12

0 Answers0