简体   繁体   中英

Time complexity for running len(array) in python?

How does Python find the length of the array? Is it stored somewhere in an internal data-structure or does it have to iterate through the entire thing to find the length?

I ask because I'm using it for a binary search which should run in O(log(n)), but this obviously doesn't make sense if I have to iterate through the whole thing just to find the length.

Lists can store their length as part of their structure. Since it only needs to be stored in one place, it can add a maximum of O(1) to all computations and therefore not be too much overhead.

Getting the length is therefore O(1) because it's just the lookup of a field.

For more information, see the docs .

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