Reputation: 81
I was going through https://wiki.python.org/moin/TimeComplexity of Lists in python. I know python list internally works as an Array. But how internally length of list is O(1)
. As it needs to traverse till end of list and increment the counter and return it.
Thanks in Advance
Upvotes: 1
Views: 542
Reputation: 81604
TL;DR lists keep track of their length.
In CPython, calling len([])
invokes the Py_SIZE
C macro, which simply returns the value of the ob_size
attribute.
static Py_ssize_t
list_length(PyListObject *a)
{
return Py_SIZE(a);
}
#define Py_SIZE(ob) (_PyVarObject_CAST(ob)->ob_size)
Upvotes: 5