Using any:
>>> data = [False, False, False]
>>> not any(data)
True
any will return True if there's any truth value in the iterable.
Using any:
>>> data = [False, False, False]
>>> not any(data)
True
any will return True if there's any truth value in the iterable.
Basically there are two functions that deal with an iterable and return True or False depending on which boolean values elements of the sequence evaluate to.
all(iterable)returns True if all elements of theiterableare considered as true values (likereduce(operator.and_, iterable)).any(iterable)returns True if at least one element of theiterableis a true value (again, using functional stuff,reduce(operator.or_, iterable)).
Using the all function, you can map operator.not_ over your list or just build a new sequence with negated values and check that all the elements of the new sequence are true:
>>> all(not element for element in data)
With the any function, you can check that at least one element is true and then negate the result since you need to return False if there's a true element:
>>> not any(data)
According to De Morgan's law, these two variants will return the same result, but I would prefer the last one (which uses any) because it is shorter, more readable (and can be intuitively understood as "there isn't a true value in data") and more efficient (since you don't build any extra sequences).
arrays - why python all([[False, True],[False, False]]) is considered True - Stack Overflow
How do Python's any and all functions work? - Stack Overflow
How "Why does all() return True if the iterable is empty?" turns on a 2,500 year old riddle in philosophy
How do while not loops work
Videos
Numpy does it in a more math-focused way where it actually looks at all the values in all the lists. The Python interpreter, on the other hand, looks at it from a programmatic way.
The reason all([[False, True],[False, False]]) evaluates to True is due to two quirks of Python.
- The
all(iterable)function looks at each element in the iterable and checks if they are all truthy. - A list that is not empty is truthy`.
The all() function checks each element in the super list and sees that it is structured [list, list]. But instead of going into each sublist, all() simply evaluates whether each sublist is "truthy". Since the sublists all have values within them, they're both truthy and thus evaluates to True. In the end, all() only sees that the super list is made of two truthy elements, and thus it returns True.
Cool question. Best way to approach this, is to try it out for oneself in a Python REPL:
$ python
[Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bool([False])
True
>>> bool(False)
False
>>> all([[]])
False
>>> all([[False]])
True
But hey, who am I but a humble raven, standing atop the shoulders of giants here. Check out this answer here for more details and clarification.
You can roughly think of any and all as series of logical or and and operators, respectively.
any
any will return True when at least one of the elements is Truthy. Read about Truth Value Testing.
all
all will return True only when all the elements are Truthy.
Truth table
+-----------------------------------------+---------+---------+
| | any | all |
+-----------------------------------------+---------+---------+
| All Truthy values | True | True |
+-----------------------------------------+---------+---------+
| All Falsy values | False | False |
+-----------------------------------------+---------+---------+
| One Truthy value (all others are Falsy) | True | False |
+-----------------------------------------+---------+---------+
| One Falsy value (all others are Truthy) | True | False |
+-----------------------------------------+---------+---------+
| Empty Iterable | False | True |
+-----------------------------------------+---------+---------+
Note 1: The empty iterable case is explained in the official documentation, like this
any
Return
Trueif any element of the iterable is true. If the iterable is empty, returnFalse
Since none of the elements are true, it returns False in this case.
all
Return
Trueif all elements of the iterable are true (or if the iterable is empty).
Since none of the elements are false, it returns True in this case.
Note 2:
Another important thing to know about any and all is, it will short-circuit the execution, the moment they know the result. The advantage is, entire iterable need not be consumed. For example,
Copy>>> multiples_of_6 = (not (i % 6) for i in range(1, 10))
>>> any(multiples_of_6)
True
>>> list(multiples_of_6)
[False, False, False]
Here, (not (i % 6) for i in range(1, 10)) is a generator expression which returns True if the current number within 1 and 9 is a multiple of 6. any iterates the multiples_of_6 and when it meets 6, it finds a Truthy value, so it immediately returns True, and rest of the multiples_of_6 is not iterated. That is what we see when we print list(multiples_of_6), the result of 7, 8 and 9.
This excellent thing is used very cleverly in this answer.
With this basic understanding, if we look at your code, you do
Copyany(x) and not all(x)
which makes sure that, atleast one of the values is Truthy but not all of them. That is why it is returning [False, False, False]. If you really wanted to check if both the numbers are not the same,
Copyprint [x[0] != x[1] for x in zip(*d['Drd2'])]
How do Python's
anyandallfunctions work?
any and all take iterables and return True if any and all (respectively) of the elements are True.
Copy>>> any([0, 0.0, False, (), '0']), all([1, 0.0001, True, (False,)])
(True, True) # ^^^-- truthy non-empty string
>>> any([0, 0.0, False, (), '']), all([1, 0.0001, True, (False,), {}])
(False, False) # ^^-- falsey
If the iterables are empty, any returns False, and all returns True.
Copy>>> any([]), all([])
(False, True)
I was demonstrating all and any for students in class today. They were mostly confused about the return values for empty iterables. Explaining it this way caused a lot of lightbulbs to turn on.
Shortcutting behavior
They, any and all, both look for a condition that allows them to stop evaluating. The first examples I gave required them to evaluate the boolean for each element in the entire list.
(Note that list literal is not itself lazily evaluated - you could get that with an Iterator - but this is just for illustrative purposes.)
Here's a Python implementation of any and all:
Copydef any(iterable):
for i in iterable:
if i:
return True
return False # for an empty iterable, any returns False!
def all(iterable):
for i in iterable:
if not i:
return False
return True # for an empty iterable, all returns True!
Of course, the real implementations are written in C and are much more performant, but you could substitute the above and get the same results for the code in this (or any other) answer.
all
all checks for elements to be False (so it can return False), then it returns True if none of them were False.
Copy>>> all([1, 2, 3, 4]) # has to test to the end!
True
>>> all([0, 1, 2, 3, 4]) # 0 is False in a boolean context!
False # ^--stops here!
>>> all([])
True # gets to end, so True!
any
The way any works is that it checks for elements to be True (so it can return True), then it returnsFalseif none of them wereTrue`.
Copy>>> any([0, 0.0, '', (), [], {}]) # has to test to the end!
False
>>> any([1, 0, 0.0, '', (), [], {}]) # 1 is True in a boolean context!
True # ^--stops here!
>>> any([])
False # gets to end, so False!
I think if you keep in mind the short-cutting behavior, you will intuitively understand how they work without having to reference a Truth Table.
Evidence of all and any shortcutting:
First, create a noisy_iterator:
Copydef noisy_iterator(iterable):
for i in iterable:
print('yielding ' + repr(i))
yield i
and now let's just iterate over the lists noisily, using our examples:
Copy>>> all(noisy_iterator([1, 2, 3, 4]))
yielding 1
yielding 2
yielding 3
yielding 4
True
>>> all(noisy_iterator([0, 1, 2, 3, 4]))
yielding 0
False
We can see all stops on the first False boolean check.
And any stops on the first True boolean check:
Copy>>> any(noisy_iterator([0, 0.0, '', (), [], {}]))
yielding 0
yielding 0.0
yielding ''
yielding ()
yielding []
yielding {}
False
>>> any(noisy_iterator([1, 0, 0.0, '', (), [], {}]))
yielding 1
True
The source
Let's look at the source to confirm the above.
Here's the source for any:
Copystatic PyObject *
builtin_any(PyObject *module, PyObject *iterable)
{
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
int cmp;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
iternext = *Py_TYPE(it)->tp_iternext;
for (;;) {
item = iternext(it);
if (item == NULL)
break;
cmp = PyObject_IsTrue(item);
Py_DECREF(item);
if (cmp < 0) {
Py_DECREF(it);
return NULL;
}
if (cmp > 0) {
Py_DECREF(it);
Py_RETURN_TRUE;
}
}
Py_DECREF(it);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
else
return NULL;
}
Py_RETURN_FALSE;
}
And here's the source for all:
Copystatic PyObject *
builtin_all(PyObject *module, PyObject *iterable)
{
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
int cmp;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
iternext = *Py_TYPE(it)->tp_iternext;
for (;;) {
item = iternext(it);
if (item == NULL)
break;
cmp = PyObject_IsTrue(item);
Py_DECREF(item);
if (cmp < 0) {
Py_DECREF(it);
return NULL;
}
if (cmp == 0) {
Py_DECREF(it);
Py_RETURN_FALSE;
}
}
Py_DECREF(it);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
else
return NULL;
}
Py_RETURN_TRUE;
}