The Python Oracle

Python all() method

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping

--

Chapters
00:00 Python All() Method
00:27 Answer 1 Score 8
00:59 Accepted Answer Score 5
01:35 Answer 3 Score 0
01:59 Thank you

--

Full question
https://stackoverflow.com/questions/1665...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 8


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.



ACCEPTED ANSWER

Score 5


As Henny said, your collection is empty, because you are only looking at those values that already fill your condition.

You want to return the results of the check, not the element if the check passed:

all(x in valid_compare_diff for x in listitem)

With (x for x in listitem if x in valid_compare_diff), you will get all those values of listitem that belong to valid_compare_diff (in your case, none).

With (x in valid_compare_diff for x in listitem), for each x, you take the value of the expression (x in valid_compare_diff), giving you a bool for every x.




ANSWER 3

Score 0


(x for x in listitem if x in valid_compare_diff)

says 'gather all the xs from listitem that are also in valid_compare_diff. Passing that through all() only cares about those xs that you did pick up, and so it will be True unless you've picked up atleast one falsey x - it doesn't care (or even know) about how you chose those xs in the first place.