0

Let's suppose you have a python list and want to convert it to an array. The most straight forward way would be to use a for loop.

And that's what I've been doing most of the time, but it clutters the code with basic operations, and I know cython is compiled python so I wonder if there's a shorthand or more pythonic way of doing it.

list = [i for i in range(10)]

cdef int * array = <int *> malloc(sizeof(int) * 10)

cdef int i

for i in range(len(list)):
    array[i] = list[i]

Is there any syntax that allows me to perform this copy in one single line?

This doesn't seem to work:

array[:] = list[:]
Jeacom
  • 102
  • 6
  • Possible duplicate of [How to convert python array to cython array?](https://stackoverflow.com/questions/11689967/how-to-convert-python-array-to-cython-array) – ead Aug 19 '19 at 20:18
  • BSO's answer https://stackoverflow.com/a/57562797/5769463 is also a solid advise. – ead Aug 19 '19 at 20:19

1 Answers1

1

I am not an expert but I think the correct way to pass a python list to a C-like array is to use the functionality of the Cython array module to copy the values to a continuous memory like this:

from cpython cimport array
import array

list = [i for i in range(10)]

cdef array.array myArray =  array.array('i', list) #we need to specify the type of the array with 'i', 'f' for float, ...

dummyFunction(myArray.data.as_ints) #this c function will receive an int *
Ben Souchet
  • 1,450
  • 6
  • 20