Paul Rubin <http://[EMAIL PROTECTED]> wrote:
> "George Sakkis" <[EMAIL PROTECTED]> writes: > > As clunky as it seems, I don't think you can beat it in terms of > > brevity; if you care about memory efficiency though, here's what I use: > > > > def length(iterable): > > try: return len(iterable) > > except: > > i = 0 > > for x in iterable: i += 1 > > return i > > Alex's example amounted to something like that, for the generator > case. Notice that the argument to sum() was a generator > comprehension. The sum function then iterated through it. True. Changing the except clause here to except: return sum(1 for x in iterable) keeps George's optimization (O(1), not O(N), for containers) and is a bit faster (while still O(N)) for non-container iterables. Alex -- http://mail.python.org/mailman/listinfo/python-list