[Solved] any() function in Python


any(list) returns a boolean value, based only on the contents of list. Both -1 and 1 are true values (they are not numeric 0), so any() returns True:

>>> lst = [1, -1]
>>> any(lst)
True

Boolean values in Python are a subclass of int, where True == 1 and False == 0, so True is not smaller than 0:

>>> True < 0
False

The statement any(list) is in no way equivalent to any(x < 0 for x in list) here. That expression uses a generator expression to test each element individually against 0, and there is indeed one value smaller than 0 in that list, -1:

>>> (x < 0 for x in lst)
<generator object <genexpr> at 0x1077769d8>
>>> list(x < 0 for x in lst)
[False, True]

so any() returns True as soon as it encounters the second value in the sequence produced.

Note: You should avoid using list as a variable name as that masks the built-in type. I used lst in my answer instead, so that I could use the list() callable to illustrate what the generator expression produces.

2

solved any() function in Python