any(), all() and empty iterable

Piet van Oostrum piet at
Wed Apr 15 03:17:56 CEST 2009

>>>>> Mark Dickinson <dickinsm at> (MD) wrote:

>MD> On Apr 14, 7:21 pm, Luis Alberto Zarrabeitia Gomez <ky... at>
>MD> wrote:
>>> It's more than that. Python's following the rules here. Maybe it could be
>>> documented better, for those without a background in logic/discrete mathematics,
>>> but not changed.

>MD> Agreed.

>MD> I'd like to guess that in 93.7% of cases, when a programmer
>MD> has used all(seq) without having thought in advance about what the
>MD> right thing to do is when seq is empty, the current behaviour is
>MD> already the right one.  I tried to test this hypothesis, but a
>MD> Google code search for uses of all() turned up very little
>MD> besides definitions.  For example:

>MD> if all(t.already_filed() for t in my_tax_forms):
>MD>     go_to_bed_happy()
>MD> else:
>MD>     file_for_extension()

>MD> In the event that you didn't have any tax_forms, this
>MD> does the right thing.

>MD> The current definition also makes reasoning about programs and
>MD> program transformations easier, thanks to invariants like:

>MD> all(seq1 + seq2) === all(seq1) and all(seq2)

>MD> and

>MD> all(all(s) for s in seqs) === all(chain(*seqs))

>MD> and

>MD> any(not s for s in seq) == not all(seq)

>MD> These invariants wouldn't hold if all([]) were False, or raised
>MD> an exception.

That is so because 'all' and 'any' are reduce (or fold) operations on the
logical operations 'and' and 'or', respectively. And the reduce
operation on an empty sequence should be the identity of the underlying
operation. The identity of 'and' is True and that of 'or' is False:
(x and True) == (True and x) == x
(x or False) == (False or x) == x
for every boolean x.
Piet van Oostrum <piet at>
URL: [PGP 8DAE142BE17999C4]
Private email: piet at

More information about the Python-list mailing list