Python Forum
what to return for an empty list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: what to return for an empty list (/thread-42184.html)



what to return for an empty list - Skaperen - May-24-2024

i have a function to test if multiple items all meet a certain condition. another function is to test if multiple items all fail to meet a certain condition. two more functions do these tests if any item (one or more) meets, or fails to meet, a certain condition. what the condition is, is fixed. for a different condition, there would be four more functions. the items are passed in a list or tuple. the return value is a boolean, True or False. if any item type does not make sense (such as passing an int when the condition being tested is if a character is an English vowel) an exception is raised (such as TypeError).

if the passed list (or tuple) is empty, should this function raise an exception or return some value? which exception? there seems to be no EmptyListError. i'd like to be sure any exception raised applies only one way or the other so the nature of the error is clear.


RE: what to return for an empty list - Gribouillis - May-24-2024

(May-24-2024, 03:38 AM)Skaperen Wrote: if the passed list (or tuple) is empty, should this function raise an exception or return some value?
The best is the rule from mathematical logic. If «any of them meets Condition», it implies that the list is not empty. Consequently, «any» should return False when the list is empty. The opposite statement should return True when the list is empty, but the opposite statement is «all of them meet not Condition». Consequently «all» must return True when the list is empty.
>>> any([])
False
>>> all([])
True



RE: what to return for an empty list - Skaperen - May-24-2024

i'm expanding these functions to also accept multiple items as individual arguments. that way the call could be done like fun([foo,bar]) or like fun(foo,bar). the functions any() and all() raise TypeError if no arguments are given. but this expanding means i need to treat fun() like fun([]) which is doable. it just doesn't have the concise analogy of any() and all().