The C Function to Iterate Over a PyList (PyObject) and Print Each Item (Python C API: PyObject_GetIter)

in python •  last year 

We can call Python code in C via the Python C API. And we want to be able to go over the items for a PyList that is type of PyObject, for example, the following "path" variable is type of PyObject, and we can insert/append item(s) to it via PyList_Append.

PyObject* path = PySys_GetObject((char*)"path");
PyList_Append(path, PyUnicode_FromString("."));

And, we can use the PyObject_GetIter and PyIter_Next method to go over each item and print them. Each element could be dynamic typed such as integer, float numbers, and unicode strings. These can be checked via PyLong_Check, PyFloat_Check and PyUnicode_Check accordingly.

bool printPyList(PyObject* arr) {
  PyObject *iter;
  PyObject *item;
  if ((iter = PyObject_GetIter(arr)) == NULL) {
    printf("List is Empty.\n");
    return false;
  }
  while ((item = PyIter_Next(iter)) != NULL) {
    if (PyLong_Check(item)) {
      long long_item = PyLong_AsLong(item);
      printf("%ld\n", long_item);
    }
    if (PyFloat_Check(item)) {
      float float_item = PyFloat_AsDouble(item);
      printf("%f\n", float_item);
    }
    if (PyUnicode_Check(item)) {
      const char *unicode_item = PyUnicode_AsUTF8(item);
      printf("%s\n", unicode_item);
    }
    Py_DECREF(item);
  }
  Py_DECREF(iter);  
  return true;
}

If the list is empty, the above function will return false. Otherwise, each element will be printed to console line by line and the function returns true.

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Blog

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order:  
  ·  last year  ·  

Congratulations, your post has been curated by @scilwa, which is the curating account for @R2cornell's Discord Community.

Manually curated by @Angelica7

logo3 Discord.png