PyListObject & C Modules
Martin v. Loewis
martin at v.loewis.de
Tue Sep 3 16:16:54 EDT 2002
jggramlich at yahoo.com (Joshua Gramlich) writes:
> I am trying to find examples of this type of activity. I've found the
> documentation at www.python.org (the C api), but I'm a bit green (new)
> and cannot read the List Objects page with any, well, usefulness.
Here is a function that gets a list as an argument, and returns a list
that has the same first element:
PyObject*
get_first_elem(PyObject *unused, PyObject *args)
{
PyObject *list;
PyObject *first;
PyObject *result;
if(!PyArg_ParseTuple("O", &list))
return NULL;
if(!PyList_Check(list)) {
PyErr_SetString(PyExc_TypeError, "get_first_elem expects a list");
return NULL;
}
if(PyList_Size(list) == 0){
PyErr_SetString(PyExc_ValueError, "empty lists not allowed");
return NULL;
}
first = PyList_GetItem(list, 0);
result = PyList_New(1);
if (!result) return NULL;
PyList_SetItem(result, 0, first);
return result;
}
The Python equivalent of this is
def get_first_elem(_list):
if type(_list) != list: raise TypeError, "expects a list"
if len(_list) == 0: raise ValueError, "must not be empty"
first = _list[0]
return [first]
HTH,
Martin
More information about the Python-list
mailing list