Exploring Examples Using not
00:00
Let’s do some negation. In its simplest use, not
inverts the truth value of a Boolean expression. So if you create two variables and then perform a comparison on them, you can see that x
is not bigger than y
.
00:24
But if you put not
in front of the comparison, the result of the entire expression, including the not
becomes True
.
00:34
And that’s the basics of what inverting a Boolean expression means. However, every expression in Python is given a truth value, so you can apply not
to other things, as well.
00:49
Most, in fact, are True
, but there are some that are considered False
. None
is False
, and of course, False
is False
.
00:58
Any numeric expression with a value of 0
is considered False
. Any empty collection is also False
. Additionally, if a class has implemented a dunder method like .__bool__()
or or .__len__()
, if .__bool__()
returns False
for that object, it’s considered False
.
01:16
Or if the length returns 0
, then that object is considered False
as well. So let’s take a look at some examples of those. 0
is considered False
, so not 0
should be True
.
01:35
Conversely, a number like 42
is True
, so not 42
should be False
. And that doesn’t change if you decide to use floating-point values
01:51 or even complex numbers.
02:05
Let’s take a look at some examples involving collections. An empty string is considered False
, so its negation should be True
.
02:16
On the other hand, a non-empty string is True
, so its inverse should be False
. The negation of an empty list is True
, while the negation of a non-empty list is False
.
02:40
Likewise, the negation of an empty dictionary is True
, and the negation of a non-empty dictionary is False
.
03:01
Next, you’ll see how not
can interact with other operations in Python.
Become a Member to join the conversation.