I am writing a Python extension using C. How can I populate an empty list inside C when the list is passed as an argument and the C function does not return the list but a different PyObject*
.
b=[]
a = c.populate(data=b)
print b
Output:
[1, 2, 3]
I appreciate your help. Thanks.
You can use the PyList_Append()
function to add individual elements to an existing Python list
object:
Append the object item at the end of list list. Return
0
if successful; return-1
and set an exception if unsuccessful. Analogous tolist.append(item)
.
Alternatively, use PyList_SetSlice()
to extend the list with items from another list
object:
Set the slice of list between low and high to the contents of itemlist. Analogous to
list[low:high] = itemlist
. The itemlist may be NULL, indicating the assignment of an empty list (slice deletion). Return0
on success,-1
on failure. Negative indices, as when slicing from Python, are not supported.