Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python any() method results

Tags:

python

Im wondering how the following result will yield True?

>>> x=['0']
>>> valid_diff=['0','1','2','3']
>>> result =any(x for each in x if x in valid_diff)
>>> result 
False

I would the expect the result to be True as the first element itself will be True.

Any thoughts, Im sure im missing something here..

like image 645
user1050619 Avatar asked Sep 06 '26 00:09

user1050619


2 Answers

You have made a typo with your variable names, you should be checking if each in valid_diff not if x in valid_diff and each for each not x for each

like image 149
jamylak Avatar answered Sep 07 '26 12:09

jamylak


Apart from the typo I think there's no need of storing each here, just use:

#returns True if any item in x is found in valid_diff
>>> any(each in valid_diff for each in x)
True

or strictly sticking to what you were trying to do then use this:

any(each in valid_diff and each for each in x)
#will return `True` only if any item found in valid_diff is a Truth value as well.

Truth Value Testing

like image 39
Ashwini Chaudhary Avatar answered Sep 07 '26 12:09

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!