This is redundant: if a list's length is 1, then it's true in a boolean context.
Also, please stop naming your lists 'l'. On a vast array of fonts, it differs only in a few pixels from '1'. Use "L" instead :)
This is redundant: if a list's length is 1, then it's true in a boolean context.
Also, please stop naming your lists 'l'. On a vast array of fonts, it differs only in a few pixels from '1'. Use "L" instead :)
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.
The `if L and` part safeguards against that.
assert l is not None and len(l) == 1Use xs. If you have multiple lists use ys etc.
This has multiple benefits over L in terms of readability anad understandability as a single-item variable names can be made to match the list naming scheme:
for x in xs:
for y in ys:
do_some_fancy_calculation(x,y)And as was mentioned the "assert l" part is defending against l being None. I suppose I could be more explicit by saying "assert l is not None and len(l) == 1".
I'm not sure why you'd defend against None anyway. Why defend against None, but not against 3.1459 or 4j or ''?
He's defending against None because calling __len__ on None results in an exception.
3.14159 also results in an exception but it's far more likely that the object passed was None than that it was a completely different type than the one expected.
FYI, None is a completely different type than the one expected.