2

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 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

6 Comments

Hm, I've checked in Python console and in my case a[0] is a[0] is True.
@VisioN With a a numpy array as in the question?
Note that this lists and other standard Python datatypes keep references to objects, but Numpy stores data in a way that doesn't require the overhead of Python objects for each array entry. This way np.array can efficiently deal with very large arrays, at the cost of having to create individual objects (that apparently bypass python's small integer cache) when indexing them.
@khelwood No, a standard list but I see the explanation from Jasmijn which makes perfect sense.
a[0] is a[0] wil surely be True for values from (IIRC) -5 to 256? Since Python stores all these by reference and a is b will always be true if a and b evaluate to be in this range?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.