简体   繁体   中英

How does len(array) work under the hood

So take an array:

x = [1,2,3,4]

How does python get the length of this array when you call

len(x)

At first glance an obvious solution seems to be that it iterates through the array and increments a counter that then says "Hey the length of the array is 4!" But this seems pretty inefficient if you have already defined an array. I believe, and correct me if I am wrong, that python already has to allocate memory for each element within the array when you initialize it, which suggests to me that it already iterates through the area upon assignment. If this were the case, it would seem like a smart idea to count the arrays length and have it allocated to memory until the instance of the array is destroyed. So when you call len(x) really it is just pointing to memory instead of iterating through the array.

I am wondering if the len() method behaves more similarly to how I described above, or if it does iterate through the array every time it is called, or something completely different.

Also if it does iterate through the array every time it is called, maybe someone out there has a cool trick for storing the length of an array when it is initialized instead of iterating through it again when len(x) is called.

This is mostly a question of curiosity. Assuming the answer is, the array is iterated every time len is called, explanations about why that is the case, and why it may be a bad idea to call your own method to do so are a bad idea will also be greatly appreciated. The more information the merrier!

The Python docs are pretty clear here (my highlighting):

Python's lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array's length in a list head structure .

Note that Python 3's FAQ has the identical text .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM