and [True,True] --> [True, True]?????

Peter Pearson ppearson at nowhere.invalid
Mon Apr 20 11:53:41 EDT 2009


On 20 Apr 2009 09:26:34 GMT, Steven D'Aprano wrote:
> On Mon, 20 Apr 2009 10:54:40 +0200, Gerhard Häring wrote:
[snip]
>> I prefer to write it explicitly:
>> 
>> if len(lst) > 0:
>
> Do you also count the length of a list explicitly?
>
> n = 0
> for item in lst:
>     n += 1
> if n > 0:
>     ...
>
> No? Of course you don't. You understand that lists know how to calculate 
> their own length, and you just ask the list for its length. Great.
>
> Well, lists also know whether or not they are empty, without needing to 
> concern yourself with the definition of "empty".
>
> if lst:
>     # not empty
> else:
>     # empty
>
> All Python objects have an understanding of "empty" or "not empty", and 
> the only time I've seen it cause problems is with iterators, because you 
> can't tell if an iterator is empty until you actually try to access a 
> value.

Like Gerhard, I prefer the construction that explicitly
says, "This is a list, and this is what I'll do if it's not
empty."  To me, and I suspect to a great many programmers,
"if x:" does *not* mean "if x is not empty", it means "if
x is (in some sense) True, including the possibility that
x is an object from which a True or False value must be
extracted by means that might not be at all obvious."  For
an object lesson in the perils of said extraction, see the
recent thread on [False,True] and [True,True] == [True,True].

People much smarter than me will no doubt rush to point out
that if I were alert, I would know from the context that x
is a list, and if I were thoroughly familiar with Python, I
would know that when x is a list, "if x:" means not empty.
True, but this is all the brain I got, so when I come back
in two months, pathetically disoriented, to peer at this
line of code through my senescent blear, I hope I'll see,
"This, Peter, is a list, and this is what I'll do . . ."

The "not empty" interpretation is a cute shortcut.  But
somebody's gotta put up some resistance to cute shortcuts,
or we'll find ourselves back with Perl.

-- 
To email me, substitute nowhere->spamcop, invalid->net.



More information about the Python-list mailing list