Re: handle for lsit constructor?

Guido.van.Rossum@cwi.nl
Fri, 04 Mar 1994 10:33:23 +0100

For manipulating Python lists from C, there's a whole load of
functions (defined in Include/listobject.h) which you can used.

In particular:

- To create a brand new empty list, you use list = newlistobject(0) --
you can also pass an argument to specify the initial number of
elements, but you *must* fill them before handing it off to the user,
since the items are initialized to NULL.

- To append an item to a list, use INCREF(item); addlistitem(list,
item). Here and below, don't do the INCREF if you've just created the
item.

- To insert an item in a list at position i, use INCREF(item);
inslistitem(list, i, item).

- To replace an existing list item at position i with a new one, use
INCREF(item); setlistitem(list, i, item).

There are also interfaces to set or delete list slices, to get a
list's size (getlistsize(list)) or an item (getlistitem(list, i), and
even to sort a list. Note that these routines assume you know what
you are doing -- in particular, non-list arguments or invalid indices
are not handled gracefully.

Also note that ALL FUNCTIONS THAT CREATE OR MODIFY AN OBJECT can
return an error condition, for which you have to check after calling
it. See the extensions manual for more info -- it also helps to study
the source for examples.

There are similar sets of functions for manipulating most built-in
types (e.g. tuples, dictionaries/mappings, numbers); check
Include/*object.h for external declarations of the available
functions, and then check Objects/*object.c for the documentation :-)

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>