如何Python计算列表长度

时间:2013-04-27 07:14:40

标签: python python-2.7

我想知道len()是如何工作的。

每次调用len()时,它是否从列表的开头到结尾计数,或者,因为list也是一个类,len()只返回列表对象中记录列表长度的变量吗? p>

另外,我希望有人可以告诉我在哪里可以找到像'len()','map()'等内置函数的源代码。

2 个答案:

答案 0 :(得分:17)

在此处下载Python 2.7源代码:http://www.python.org/getit/releases/2.7.4/

list已在./Include/listobject.h./Objects/listobject.c中实施。

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     */
    Py_ssize_t allocated;
} PyListObject;

list.__len__()只是咨询ob_sizePyObject_VAR_HEAD的一部分。这使len()成为列表的常量操作。

答案 1 :(得分:1)

好的,你可以找到内置函数here的文档。

list数据类型跟踪它所持有的元素数量,len(list)是O(1)操作。


对于源代码,您可以在the download page找到Python的源代码。

相关问题