1

I have created 2 numpy arrays.

  1. Original
  2. Cloned

Cloned is a copy of original array. I changed an element in cloned array. I am checking id of original and cloned array using is keyword. It returns false. But when I print id of both elements, it is same.

I know about peephole optimization techniques and numbers from -5 to 256 is stored at same address in python. But here I have changed value to 400 (> 256). Still it shows same id. WHY?

Please correct me if I am wrong. I am new to numpy arrays

import numpy as np

original = np.array([
    [1, 2, 3, 4, 5],
    [6, 7, 9, 10, 11]
])


# Copying array "original" to "cloned"
cloned = original.copy()

# Changing first element of Cloned Array
cloned[0, 1] = 400

print(id(cloned[0, 1]))
print(id(original[0, 1]))

print(id(cloned[0, 1]) is id(original[0, 1]))

Output:

140132171232408 id is same

140132171232408 id is same

False is returns false although id is same

ajinzrathod
  • 925
  • 10
  • 28
  • `original[0,1]` is numpy object created on-the-fly to show the value at that slot. It is not the value, nor the location in the array. So its `id` doesn't tell you any thing useful, – hpaulj Jun 22 '20 at 14:48
  • See my answer to https://stackoverflow.com/questions/40196986/numpy-arrays-changing-id – hpaulj Jun 22 '20 at 15:30

1 Answers1

0

The is keyword is used to test if two variables refer to the same object, not to check if they are equal. Use == instead as following:

print(id(cloned[0, 1]) == id(original[0, 1]))
# Returns True

Apparently id() function return the same value but different objects therefore using is operator does not work.

  • My partial solved is solved. Thank you for that. My another question is that why `id` is same? Although 400 and 2 are two different values. – ajinzrathod Jun 22 '20 at 11:47