len() on mutables vs. immutables

Discussion in 'Python' started by Demian Brecht, Oct 18, 2012.

  1. 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
     
    Demian Brecht, Oct 18, 2012
    #1
    1. Advertisements

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steven K

    Use of LEN()

    Steven K, Apr 5, 2004, in forum: ASP .Net
    Replies:
    3
    Views:
    979
    Lloyd Sheen
    Apr 5, 2004
  2. Massimiliano Alberti

    limits.h and int len

    Massimiliano Alberti, Feb 18, 2004, in forum: C Programming
    Replies:
    18
    Views:
    931
    Michael Wojcik
    Feb 24, 2004
  3. Jeff Wagner

    String length ... len(str)

    Jeff Wagner, Dec 4, 2003, in forum: Python
    Replies:
    7
    Views:
    518
    Dennis Lee Bieber
    Dec 4, 2003
  4. Tor Erik Soenvisen
    Replies:
    14
    Views:
    791
    Tim Roberts
    Nov 23, 2006
  5. rekkufa
    Replies:
    3
    Views:
    419
  6. Replies:
    3
    Views:
    297
    Terry Reedy
    Jan 8, 2008
  7. maestro
    Replies:
    1
    Views:
    423
    Chris
    Aug 11, 2008
  8. Demian Brecht
    Replies:
    0
    Views:
    146
    Demian Brecht
    Feb 8, 2013
Loading...