Skip to main content
Engineering LibreTexts

19.4: any and all

  • Page ID
    40846
  • Python provides a built-in function, any, that takes a sequence of boolean values and returns True if any of the values are True. It works on lists:

    >>> any([False, False, True])
    True
    

    But it is often used with generator expressions:

    >>> any(letter == 't' for letter in 'monty')
    True
    

    That example isn’t very useful because it does the same thing as the in operator. But we could use any to rewrite some of the search functions we wrote in Section 9.3. For example, we could write avoids like this:

    def avoids(word, forbidden):
        return not any(letter in forbidden for letter in word)
    

    The function almost reads like English, “word avoids forbidden if there are not any forbidden letters in word.”

    Using any with a generator expression is efficient because it stops immediately if it finds a True value, so it doesn’t have to evaluate the whole sequence.

    Python provides another built-in function, all, that returns True if every element of the sequence is True. As an exercise, use all to re-write uses_all from Section 9.3.

    • Was this article helpful?