The Python Oracle

How is the memory allocated for numpy arrays in python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Switch On Looping

--

Chapters
00:00 Question
02:13 Accepted answer (Score 5)
02:48 Thank you

--

Full question
https://stackoverflow.com/questions/5726...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy #memory #mpi4py

#avk47



ACCEPTED ANSWER

Score 5


Numpy array saves its data in a memory area seperated from the object itself. As following image shows:

enter image description here

To get the address of the data you need to create views of the array and check the ctypes.data attribute which is the address of the first data element:

import numpy as np
a = np.zeros((3, 2))
print(a.ctypes.data)
print(a[0:1, 0].ctypes.data)
print(a[0:1, 1].ctypes.data)
print(a[1:2, 0].ctypes.data)
print(a[1:2, 1].ctypes.data)