Re:Python idiom for taking the single item from a list
by jemfinch on Tuesday September 28, 2010 @12:17AM
(#1734543)
You are aware that asserting `len(L) == 1` excludes the possibility that it's empty, right? You know what "redundant" means, right?
Re:Python idiom for taking the single item from a list
by statictype on Tuesday September 28, 2010 @01:51AM
(#1734724)
if L is None then asserting `len(L)==1` throws an exception.
The `if L and` part safeguards against that.
Re:Python idiom for taking the single item from a list
by jemfinch on Tuesday September 28, 2010 @01:46PM
(#1736518)
And the point that was made in the other branch of this thread is that if the author intends to guard against None (who knows why?) then he should say, explicitly, "if L is not None". That's what PEP8 recommends precisely to avoid ambiguities such as these.
In a boolean context, the list is true if the length is non-zero. This example and the one the article is about is for the case where you know the list to have exactly one element. Not zero and not more than one.