In Python, how do you explain the expression 'x = not x'

5

I already know the result, but I would like to understand what happens, why this result ...

For example:

>>> a = True
>>> b = not a    
>>> print(b)
False

It's a simple thing, but I feel annoyed to use something without knowing how it works.

    
asked by anonymous 13.11.2014 / 10:50

1 answer

7

The precedence of the operators = and not is such that the statement quoted must be interpreted as:

=(b, not(a))

i.e. "evaluate not(a) and save result to b ".

The expression not(x) returns True if x is false in a boolean context, or False if x is true in this context. In Python, the following values are considered "false":

False
None
0
0.0
-0.0
""
[]
()
{}
class MinhaClasse(object):
    def __bool__(self): # Python 3
        return False
    def __nonzero__(self): # Python 2
        return False

The remaining values are considered "true."

As a is one of the true values ( True ), then not(a) evaluates to False , and this is the value that is stored in b .

If the same variable was used (as in the title of your question), of course all the evaluation on the right side would occur before the assignment to the left side:

>>> x = True
>>> x = not x   # x é True; not(True) é False; guarde False em x => x é False.
>>> print(x)
False

Note that the result of not(x) will always be True or False , only, unlike operators like and or or that always return one of the original values:

>>> 1 and "teste"   # Verdadeiro(1) E Verdadeiro(2) é Verdadeiro(2)
'teste'
>>> {} and True     # Falso(1) E Verdadeiro(2) é Falso(1) => curto-circuito
{}
>>> False or []     # Falso(1) OU Falso(2) é Falso(2)
[]
>>> 42 or None      # Verdadeiro(1) OU Falso(2) é Verdadeiro(1) => curto-circuito
42
    
13.11.2014 / 11:14