我想知道len()是如何工作的。
每次调用len()时,它是否从列表的开头到结尾计数,或者,因为list也是一个类,len()只返回列表对象中记录列表长度的变量吗? p>
另外,我希望有人可以告诉我在哪里可以找到像'len()','map()'等内置函数的源代码。
答案 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_size
,PyObject_VAR_HEAD
的一部分。这使len()
成为列表的常量操作。
答案 1 :(得分:1)