r/learnpython • u/BluishMontoya • Sep 13 '26
Cython memoryviews?
I'm using a function I've compiled with cython, and I have to pass it a few very long lists. I'm pretty sure I should be using memoryviews, but do I convert the lists to memoryviews in the python part of my program or the cython part? It would be way better if I could do it in the python part because I'm passing the same lists to the function a few million times.
4
Upvotes
View all comments
Show parent comment
1
u/futura-bold Sep 13 '26
Oh, OK.
Regarding memoryviews, then. Generally you'd want to work with numpy arrays rather than lists as somebody's already said. Avoid accessing the individual numpy array elements within Python, though, because that's slow. You'd pass the numpy array to the cython function (which is by reference, not a copy), and the function wouldn't "convert" the array to a memoryview, as such -- it'd use the memoryview for a faster access to the memory locations within the numpy array.
If for some reason, you must access the individual array elements when setting up the arrays in pure python, then yes, you might have to set it up as a list and then convert it to a numpy array.