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[:]
2

1 Answer 1

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

Comments

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.