>>> l = [] >>> l.append(1) >>> l.append(2) >>> l.append(3) >>> l [1, 2, 3] >>> for e in l: ... print e ... 1 2 3
typedef struct { PyObject_VAR_HEAD PyObject **ob_item; Py_ssize_t allocated; } PyListObject;
/* size - */ PyList_New(Py_ssize_t size) { // nbytes = size * sizeof(PyObject *); // ob_item if (size <= 0) op->ob_item = NULL; else { op->ob_item = (PyObject **) PyMem_MALLOC(nbytes); memset(op->ob_item, 0, nbytes); } // op->allocated = size; return (PyObject *) op; }
/* self - v - */ app1(PyListObject *self, PyObject *v) { // , - (-1) if (list_resize(self, n+1) == -1) return -1; // , n v PyList_SET_ITEM(self, n, v); // 0 return 0; }
/* self - newsize - */ list_resize(PyListObject *self, Py_ssize_t newsize) { // - if (allocated >= newsize && newsize >= (allocated >> 1)) { assert(self->ob_item != NULL || newsize == 0); Py_SIZE(self) = newsize; return 0; } /* , * */ new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); /* */ if (new_allocated > PY_SIZE_MAX - newsize) { PyErr_NoMemory(); return -1; } else { new_allocated += newsize; } // if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *))) PyMem_RESIZE(items, PyObject *, new_allocated); return 0; }
/* self - where - , v - */ ins1(PyListObject *self, Py_ssize_t where, PyObject *v) { n = Py_SIZE(self); // if (list_resize(self, n+1) == -1) return -1; // , if (where < 0) { where += n; if (where < 0) where = 0; } // , if (where > n) where = n; // items = self->ob_item; for (i = n; --i >= where; ) items[i+1] = items[i]; // items[where] = v; return 0; }
/* self - args - , */ listpop(PyListObject *self, PyObject *args) { // Py_ssize_t i = -1; // - NULL if (Py_SIZE(self) == 0) { return NULL; } // - if (i < 0) i += Py_SIZE(self); v = self->ob_item[i]; // - list_resize if (i == Py_SIZE(self) - 1) { status = list_resize(self, Py_SIZE(self) - 1); return v; } // , status = list_ass_slice(self, i, i+1, (PyObject *)NULL); return v; }
/* self - v - */ listremove(PyListObject *self, PyObject *v) { Py_ssize_t i; // for (i = 0; i < Py_SIZE(self); i++) { int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); // - Python None if (cmp > 0) { if (list_ass_slice(self, i, i+1, (PyObject *)NULL) == 0) Py_RETURN_NONE; return NULL; } else if (cmp < 0) return NULL; } // - NULL return NULL; }
Source: https://habr.com/ru/post/273045/
All Articles