1

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.

asked Jun 7, 2016 at 3:38
2

1 Answer 1

4

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.

answered Jun 7, 2016 at 3:50
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.