Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #38399 > unrolled thread

Re: len() on mutables vs. immutables

Started byTerry Reedy <tjreedy@udel.edu>
First post2013-02-07 23:30 -0500
Last post2013-02-07 23:30 -0500
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: len() on mutables vs. immutables Terry Reedy <tjreedy@udel.edu> - 2013-02-07 23:30 -0500

#38399 — Re: len() on mutables vs. immutables

FromTerry Reedy <tjreedy@udel.edu>
Date2013-02-07 23:30 -0500
SubjectRe: len() on mutables vs. immutables
Message-ID<mailman.1470.1360297894.2939.python-list@python.org>
On 2/7/2013 8:09 PM, Demian Brecht wrote:

> http://demianbrecht.github.com/posts/2013/02/07/understanding-len/

> When len() is called passing an immutable built-in type (such as a
> string), I'd assume that the overhead in doing so is simply a function
> call and there are no on-call calculations done. Is that correct?
>
> I'd also assume that mutable built-in types (such as a bytearray) would
> cache their size internally as a side effect of mutation operations. Is
> that correct? If so, is it safe to assume that at least all built-in
> types observe this behavior, or are there some that incur an O(n) cost
> on every len() call?

The language specification specifies behavior, not resource usage. 
However, CPython's concrete collection classes all require knowing how 
many items they contain for their operation. And they 'know' that they 
must respond to len() inquiries (including for truth value) and for 
sequences, deal with index and slice operations. So you may assume that 
len() simply accesses a private internal attribute.

Keep in mind that 'immutables' have to be internally mutated to set 
their values, so from the interpreter viewpoint, there is little 
difference between mutable and immutable. The latter simply lack 
publicly accessible mutation methods.

--
Terry Jan Reedy

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web