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


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.

1
2
PyObject* path = PySys_GetObject((char*)"path");
PyList_Append(path, PyUnicode_FromString("."));
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;
}
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) —

GD Star Rating
loading...
316 words
Last Post: 5 Things to Look For in a WordPress Hosting Provider
Next Post: Teaching Kids Programming - Algorithms to Compute the Alternating Digit Sum

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

Leave a Reply