0

I always believed that, in python, the syntax a=b applied the value of b to a. Although, in the example below, the value of image_init seems to be updated, what am I missing here??

import numpy as np
img = np.zeros((3,3))
img_init = img
img[-1,:]=[1]
print img
print
print img_init

Output:

[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]]

[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]]

EDIT: Let me correct a bit the question. First, both img and img_init are numpy array, not list. Then, I'm not looking for a way to copy the list, I'm just looking for the reason why img_init gets updated, Thanks already for all the answers!

Arno
  • 331
  • 2
  • 4
  • 8
  • Use `img_init = copy.deepcopy(img)` – Bhargav Rao Dec 08 '14 at 14:46
  • 3
    No; all names in Python reference objects; `a=b` makes the name `a` reference the same object as the name `b`. – chepner Dec 08 '14 at 14:48
  • That indeed seems a possibility, but I was more looking at the reason why the value of image_init get updated, while, in my point of view, it shouldn't... isn't it? – Arno Dec 08 '14 at 14:49
  • possible duplicate of [numpy array assignment problem](http://stackoverflow.com/questions/3059395/numpy-array-assignment-problem) – Ashwini Chaudhary Dec 08 '14 at 14:49
  • that can't be chepner, try a=1 b=a a=2 print a print b – Arno Dec 08 '14 at 14:51
  • 3
    @Arno Integers are immutable. – Ashwini Chaudhary Dec 08 '14 at 14:53
  • Moreover, `a = [1]` `b = a` `a = [2]` will still behave the same as your example. *Reassigning* `a` after making `b` a reference to the same object as `a` has no effect on `b`. It's only changing *properties* of the object pointed to that seems confusing. Integers don't have properties. – Ian McLaird Dec 08 '14 at 14:58
  • Consider reading http://nedbatchelder.com/text/names.html – jonrsharpe Dec 08 '14 at 15:03
  • 1
    I don't agree that this question is a duplicate as marked, and I think the highest-voted answers to the linked question miss the real meat of the question here, which is "Why does my variable behave like a pointer?" OP doesn't care *how* to copy the list (or object or whatever), he wants to know *why he has to*. – Ian McLaird Dec 08 '14 at 15:17

0 Answers0