How do Python's any and all functions work?

后端 未结 8 1563
挽巷
挽巷 2020-11-22 01:13

I\'m trying to understand how the any() and all() Python built-in functions work.

I\'m trying to compare the tuples so that if any value i

8条回答
  •  误落风尘
    2020-11-22 01:52

    I know this is old, but I thought it might be helpful to show what these functions look like in code. This really illustrates the logic, better than text or a table IMO. In reality they are implemented in C rather than pure Python, but these are equivalent.

    def any(iterable):
        for item in iterable:
            if item:
                return True
        return False
    
    def all(iterable):
        for item in iterable:
            if not item:
                return False
        return True
    

    In particular, you can see that the result for empty iterables is just the natural result, not a special case. You can also see the short-circuiting behaviour; it would actually be more work for there not to be short-circuiting.

    When Guido van Rossum (the creator of Python) first proposed adding any() and all(), he explained them by just posting exactly the above snippets of code.

提交回复
热议问题