2

The code below:

import numpy as np
x=np.array([1,-1,-1,1])
y = 0.5 * (x + 1)
id(x[0])==id(y[0])

The output is True, however if I assign a new value to x[0]=1212, the output of

id(x[0])==id(y[0])

is also True. However the values of x[0] and y[0] is different. Why?

Booma
  • 261
  • 6
  • 19
Liang Xiao
  • 21
  • 3
  • Even more interesting: `id(x[0]) == id(y[2])`, which is also always true, regardless of re-assignment. All of this is only true for `numpy.ndarray`s, normal `list`s behave as you would expect. – Graipher Apr 16 '18 at 12:15
  • 2
    `x[0]`, creates a *new* Python object representing that value. As soon as the LHS `id(x[0])` is computed, and *before* the RHS is computed, the refcount of the Python object `x[0]` drops to 0 and the memory it occupied can be reused. When `y[0]` is created, it just uses the memory that `x[0]` occupied. There's a duplicate question somewhere... – Alex Riley Apr 16 '18 at 12:32

1 Answers1

0

The answer is with in the definition of the id itself.

What is the number returned from the id function?

It is "an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime." (Python Standard Library - Built-in Functions) A unique number. Nothing more, and nothing less.

Based on above definition, the id will remain same irrespective of its value. Hope that helps you.

  • 1
    id is the memory position of a variable, right ? How two variables have the different values on the same memory position? – Liang Xiao Apr 16 '18 at 11:13