Just now, I wanted to define the all function in Python, which takes a sequence as its argument and returns True iff no element of the sequence is False. My instinct was to do it with reduce:

all = lambda seq: reduce(and, seq, True)

But and is a syntactic keyword, so that doesn't work. However, abusing the fact that Python follows Iverson's convention, we can map int.__mul__ instead:

all = lambda seq: reduce(int.__mul__, seq, True)

Evil, delicious evil. Do check out David Jones' weblog if you haven't already, it's really interesting. I started reading it the other day and couldn't stop :)

9 responses

  1. duff says:

    A more readable approach would be to use "operator.and_".

  2. wingo says:

    duff: You speak the truth. I'm just amused that you can multiply by False.

  3. Rob Bradford says:

    Or, better:

    all = lambda seq: reduce(bool.__and__, seq, True)

    This is better because it returns True or False not 0 or 1.

  4. Phil says:

    FYI, all is built-in in Python 2.5.

  5. Josh says:

    all = lambda seq: False not in seq

  6. Johan Dahlin says:

    Josh: or rather,

    all = lambda seq: False not in map(bool, seq)

  7. Josh says:

    If you want the same behavior as the built-in all function, you are correct. Andy's requirement "returns True iff no element of the sequence is False" is not clear as to whether he means False or anything that converts to False.

    built-in: all((True, None)) returns False

    It could be argued that no element in that sequence is "False". My solution would return True. I could not think of a simple way around 0 == False. i.e. my all((True, 0)) returns False like yours.

  8. Pádraig Brady says:

    Johan, you want 'itertools.imap' instead of 'map'
    to have the same functionality as the builtin all()
    available since python 2.5.

    I've been playing with that here:

    Andy, Your's is the only site I've noticed that I
    can't connect to from home. Though I can connect to
    it from work?

  9. wingo says:

    Pádraig: Hm, I don't know anything about that. If you get a chance, can you send me a mail (wingo pobox com) with the traceroute from home?

Comments are closed.