0

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
zitro
  • 3
  • 1

1 Answers1

0

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 to list.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). Return 0 on success, -1 on failure. Negative indices, as when slicing from Python, are not supported.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank you very much Martijn. I tried and like the PyList_Append() solution you advised to me. Do you know how can I set the size of the list to empty in C code (not in Python side) so that if the c.populate is inside a Python loop the b buffer would not grow bigger and bigger. Thanks again. – zitro Jun 16 '14 at 18:17
  • Use `PyList_SetSlice()` with `itemlist` set to `NULL`, `low` set to `0` and `high` set to `Py_SIZE` of the list. – Martijn Pieters Jun 16 '14 at 18:20
  • Sorry I might have missed your PyList_SetSlice() recommendation. I tried it and it worked brilliantly for my purpose. Thank you very much Martijn. – zitro Jun 16 '14 at 18:54