[Python-ideas] Variations on a loop

Steven Bethard steven.bethard at gmail.com
Sat Aug 30 18:05:44 CEST 2008


On Sat, Aug 30, 2008 at 12:49 AM, Bruce Leban <bruce at leapyear.org> wrote:
>
> On Fri, Aug 29, 2008 at 7:17 PM, Steven Bethard <steven.bethard at gmail.com>
> wrote:
>>
>> On Fri, Aug 29, 2008 at 6:25 PM, Bruce Leban <bruce at leapyear.org> wrote:
>> > Not quite: len(items) requires iterating across the entire list which
>> > may
>> > not be necessary or desirable. Plus you may need an intermediate
>> > variable to
>> > store it. I think that's inferior.
>>
>> If len(items) requires iterating across the entire list, then you're
>> not using a Python list object, you're using someone else's (poorly
>> implemented) list data structure. Python lists give len(obj) in O(1).
>
> items need not be a literal list. If you can compute this
>    len([t for t in range(100) if foo(t)]):
> without iterating over the list, then there's a Turing award waiting for
> you. :-)

See what you said above: "len(items) requires iterating across the
list". The list comprehension is iterating over the items, not the
call to len(). So I *can* compute "len(items)" without iterating over
the list.

Steve
-- 
I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
 --- Bucky Katt, Get Fuzzy



More information about the Python-ideas mailing list