Python array id value

Viewed 2123

Why does the id() function returning the same value for the alternate elements of the array in python? I use the following code

import numpy as np

a = np.array([3, 6, 9, 12,5])
print('array id\t',id(a))
print(a[0],'\t',id(a[0]))
print(a[1],'\t',id(a[1]))
print(a[2],'\t',id(a[2]))
print(a[3],'\t',id(a[3]))
print(a[4],'\t',id(a[4]))

and I got the output as follows:

array id     59184176
3    200295200
6    200295136
9    200295200
12   200295136
5    200295200
1 Answers

This is particular to the way numpy arrays work. Data is stored in an efficient way that doesn't incur the cost of storing objects for each element. Instead, objects are created on demand when you read them from the array.

That means that each time you do a[0] etc., a new object is created and returned. If you don't keep a reference to it, the object is discarded, and the id becomes available to be reused. So in your case, a little while later, you get another object with the same id.

You can tell that a[0] creates a new object each time it is called, because just trying

a[0] is a[0]

evaluates to false (at least when I try it).

Alternatively, if you got references to all the objects you get from the array simultaneously, they would all have different ids.

[id(x) for x in a]
# [4538316976, 4538316784, 4538317168, 4538317200, 4538317296]
Related