Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python all() method

Tags:

python

I'm wondering how the below result yields True.None of the condition is True?

Any inputs?

>>> listitem=['a','h','o','t']
>>> valid_compare_diff
['0', '1', '2', '3', '4']
>>> all(x for x in listitem if x in valid_compare_diff)
True

New changes:-

>>> listitem=['0']
>>> valid_compare_diff
['0', '1', '2', '3', '4']
>>> all(x for x in listitem if x in valid_compare_diff)
True

How come the results are still True when the list comprehension yield a result..??

like image 995
user1050619 Avatar asked Dec 12 '22 15:12

user1050619


1 Answers

The comprehension will be empty as no value of x meets the condition:

if x in valid_compare_diff

Hence:

>>> [x for x in listitem if x in valid_compare_diff]
[]

results in [], which when passed to all returns True

>>> all([])
True

This is so because the definition of all states that if the iterable passed to it is empty then it returns True:

all(...)
    all(iterable) -> bool

    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.
like image 85
HennyH Avatar answered Dec 30 '22 13:12

HennyH