[Python] Why Python's `all` built-in function returns `True` when checking if an empty string...

Discussão em 'Python' iniciado por Stack, Maio 4, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote a function that checks if every character on a given string is also present in an arbitrary list. The code works for most cases, but when the input is an empty string, the built-in function all evaluates to True, even though that value isn't present at the ITEMS list:

    ITEMS = ['a', 'b', 'c', 'd']

    def check_all_chars_are_in_list(string):
    return all(char in ITEMS for char in string)


    if __name__ == "__main__":
    print(check_all_chars_are_in_list('saban')) # False, as expected. (1)
    print(check_all_chars_are_in_list('abcd')) # True, as expected. (2)
    print(check_all_chars_are_in_list('')) # True (why?). (3)



    I performed a manual test as to try and understand that behavior. I simply checked the in assertion via the terminal:

    >>> st = ''
    >>> l = ['a', 'b', 'c', 'd']
    >>> st in l
    False # As expected


    But I got the expected False value, so how come the example (3) on my code evaluates to True? Can someone explain that to me, please?

    Thank you!

    Continue reading...

Compartilhe esta Página