user1050619
user1050619

Reputation: 20896

Python all() method

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..??

Upvotes: 4

Views: 3226

Answers (3)

HennyH
HennyH

Reputation: 7944

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.

Upvotes: 8

lvc
lvc

Reputation: 35089

(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.

Upvotes: 0

pascalhein
pascalhein

Reputation: 5856

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.

Upvotes: 5

Related Questions