The quest started from a simple LeetCode problem. I am learning python and trying to solve a problem in leetcode where I have used len() while checking the condition in while loop. I got curious if I write len(nums) in while will my program do more computations. To find this out I started looking for the source code.
while i < len(nums):
#if both the numbers are same we can pop the ith number
#else just increase the index and return the length in the end.
if nums[i] == val:
nums.pop(i)
else:
i+=1
return len(nums)
Now, I have 2 question:
- How to look for the source code of builtin functions without manually searching the source code on GitHub?
- How len function works internally?
I have 2 assumptions for it:
- Python treat every thing as an object and they have a property called length(or something like that) and whenever I pop an element from list. This property get decremented by 1.
- Another assumption is python in someway iterates over the whole object and return the length.
I got the source code. However, again it's using another function to calculate the length.
static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
Py_ssize_t res;
res = PyObject_Size(obj);
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
return PyLong_FromSsize_t(res);
}
@Antti Haapala did a great job in explaining the answer. However, It doesn't answer my question.
These are some of the relevant question that I found on the stack overflow: