len() on mutables vs. immutables

D

Demian Brecht

I'm curious as to the implementation (I'd be happy to dig through the
source, just don't have the time right now). I've seen various
implementations across interpreters in the past (some which have been
rather shocking) and I'd like to get some insight into Python (well,
CPython at this point anyway).

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?

Obviously this can't be controlled with custom types that implement
their own __len__, I'm only asking about Python's built-ins.

Thanks,
Demian
@demianbrecht
http://demianbrecht.github.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top