title: How does len(array) work under the hood
body: <p>So take an array:  </p>
  
  <pre><code>x = [1,2,3,4]
  </code></pre>
  
  <p>How does python get the length of this array when you call </p>
  
  <pre><code>len(x)
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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!</p>