Implicit conversion to boolean in if and while statements

Ranting Rick rantingrickjohnson at
Mon Jul 16 04:41:34 CEST 2012

On Jul 15, 9:13 pm, Steven D'Aprano <steve
+comp.lang.pyt... at> wrote:

> I have just written a bunch of code with about two dozen examples similar
> to this:
> for item in (seq or []):
>     do_something_with(item)
> iterates over seq if it is non-empty, or the empty list. Writing it like
> this would be more painful, more complex, less readable and less
> idiomatic:
> if seq is not None:
>     for item in seq:
>         do_something_with(item)
> not to mention completely unnecessary if you have already checked that
> seq is either None or a sequence, and not some other arbitrary value.

Short circuitry is a powerful tool! But why the heck would your
sequences ever be None? Are you using None as a default? And if so,
why not use an empty sequence instead ([], {}, "")?

More information about the Python-list mailing list