Formal definition of operations = and ==

Asked

Viewed 126 times

1

What is the formal definition of the use of = and of == in Python? I can identify in the examples when I have to use which, but when I try to identify these operations by a formal definition as (more or less like a mathematical concept) I curl up.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

3 answers

6

It’s very simple, the = is a allocation operator, you should only use it to store a value in a variable. The left-hand operand should always be a variable, nothing more. Already the right operand accepts a value coming from a literal, a variable (another or the same, although it does not make much sense to be the same) or an expression that will be executed and its result will generate a value, and the final value obtained will be saved in the variable.

The == is a comparison operator. The two sides can be variable, literal or diverse expressions. Always try to identify that the final value obtained on the left is equal to the final value obtained on the right side. The result of the comparison operation will be of the boolean type, that is, it will be True or False. It is very common to use it a one if or while, but it doesn’t have to be so, it can be used anywhere waiting for a boolean, even can be used on the right side of the = and assign this value to a variable or you can use it to print something or pass it as an argument in a function.

The concept is valid for essentially any language.

x = 1 == 2

This is an example where x worth False because it is assigning in the variable what is on the right side that is a comparison if they are equal values, which obviously they are not. To understand a little better we can do this, although unnecessary by precedence the associativity of operators:

x = (1 == 2)

I put in the Github for future reference.

2

Well, I can’t imagine a more formal definition than official language documentation. So let’s go to it:


Assignment Statements

The = is called assignment statement (declaration of award), the definition of which is:

Assignment statements are used to (re)bind Names to values and to Modify Attributes or items of mutable Objects

That is, it serves to link (or revincular) names to their respective values, and also to modify attributes of mutable objects.

Technically speaking, the = is just a part of assignment statement, since this is also composed of the parts that come before and after the =:

assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)
target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" [target_list] ")"
                     | "[" [target_list] "]"
                     | attributeref
                     | subscription
                     | slicing
                     | "*" target

I will not list all possibilities, but just to give some examples:

# atribuir um valor a uma variável
x = 1
# atribuir um valor a várias variáveis de uma vez
x = y = z = 1

lista = [1, 2, 3, 4, 5]
# mudar valor de uma posição da lista
lista[2] = 10
# slice, muda um pedaço da lista
lista[1:4] = [ 8 ]
print(lista) # [1, 8, 5]

dic = { 'nome': 'Fulano', 'idade': 42 }
# mudar o valor da chave de um dicionário
dic['nome'] = 'Ciclano'
# ou, adicionar uma nova chave
dic['email'] = '[email protected]'
print(dic) # {'nome': 'Ciclano', 'idade': 42, 'email': '[email protected]'}

lista = [1, 2, 3, 4, 5]
# x recebe 1, y recebe 2, resto recebe o restante da lista [3, 4, 5]
x, y, *resto = lista

x = 1
y = 2
# troca os valores de x e y
x, y = y, x

Remembering that the right side of an assignment may be any valid expression that is compatible with the left side (for example, in x, y = lista, the list must have at least two elements, otherwise).

It is also worth remembering that the = is not an operator (in some languages is, but not in Python), so much so that in Python 3.8 the Assignment Expression, defining the operator := and has some differences with respect to = (just see that the Table of Operators Precedence has the :=, but it doesn’t have the =).


Equalizer

The == is one of the comparison operators, that in this case checks whether the values of the operands are equal.

Recalling that the Data Model of language defines the "value" of an object in a very abstract way, because it depends a lot on the types involved. In documentation all rules for native types are described (for example, numbers in general can be compared between different types: a int and a float may be equal, etc).

Finally, any class you create can overwrite the method __eq__ and define its own algorithm to determine whether two objects are equal. Basically, x == y flame x.__eq__(y). If you do not overwrite this method, it calls the implementation of object, who uses the operator is (which considers two objects equal only if they are the same object).

An important detail is that the operator == always returns a boolean (True or False), but the method __eq__ can return any value:

By Convention, False and True are returned for a Successful comparison. However, These methods can Return any value, so if the comparison Operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.


So they’re very different things. A didactic way of thinking is:

  • nome = algo is saying to Python who nome receives the amount algo - is a statement (or if you prefer, an order: "put the value algo in the variable nome")
  • nome == algo is asking to Python if the value of nome is algo - and the answer will be yes or no (True or False, which is the result of the expression)

1

"=" Does the assignment.

"==" Make the comparison.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.