Python | a += b no siempre es a = a + b

En python a += b no siempre se comporta de la misma manera que a = a + b, los mismos operandos pueden dar resultados diferentes bajo diferentes condiciones. Pero para comprender por qué muestran comportamientos diferentes, debe profundizar en el funcionamiento de las variables.

Entonces, primero, necesita saber qué sucede detrás de escena. 

Creando nueva variable:

Python3

a = 10
print(" id of a : ", id(10) ," Value : ", a  )

Producción :

id of a :  11094592  Value :  10

Aquí, en el ejemplo anterior, el valor 10 se almacena en la memoria y su referencia se asigna a a. 

Modificando la variable:

Python3

a = 10  # Assigning value to variable creats new object
print(" id of a : ", id(a) ," Value : ", a  )
 
a = a + 10 # Modifying value of variable creats new object
print(" id of a : ", id(a) ," Value : ", a  )
   
a += 10 # Modifying value of variable creats new object
print(" id of a : ", id(a) ," Value : ", a  )

Producción : 

id of a :  11094592  Value :  10
id of a :  11094912  Value :  20
id of a :  11095232  Value :  30

Como cada vez que creamos o modificamos int, float, char, string, crean nuevos objetos y asignan su referencia recién creada a sus respectivas variables.

Pero el mismo comportamiento no se ve en la lista.

Python3

a = [0, 1] # stores this array in memory and assign its reference to a
print("id of a: ",id(a) , "Value : ", a )
 
a = a + [2, 3] # this will also behave same store data in memory and assign ref. to variable
print("id of a: ",id(a) , "Value : ", a )
 
a += [4, 5]
print("id of a: ",id(a) , "Value : ", a )
 
#But now this will now create new ref. instead this will modify the current object so
# all the other variable pointing to a will also gets changes

 Producción: 

id of a:  140266311673864 Value :  [0, 1]
id of a:  140266311673608 Value :  [0, 1, 2, 3]
id of a:  140266311673608 Value :  [0, 1, 2, 3, 4, 5]  

En este punto puedes ver la razón por la cual a = a + b algunas veces es diferente de a += b.

Considere estos ejemplos para la manipulación de listas: 
Ejemplo 1: 

Python3

list1 = [5, 4, 3, 2, 1]
list2 = list1
list1 += [1, 2, 3, 4] # modifying value in current reference
 
print(list1)
print(list2) # as on line 4 it modify the value without creating new object
             # variable list2 which is pointing to list1 gets changes

Producción: 

[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1, 1, 2, 3, 4]

Ejemplo 2 

Python3

list1 = [5, 4, 3, 2, 1]
list2 = list1
list1 = list1 + [1, 2, 3, 4]
 
# Contents of list1 are same as above
# program, but contents of list2 are
# different.
print(list1)
print(list2)

Producción: 

[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1]

  • expresión lista1 += [1, 2, 3, 4] modifica la lista en el lugar, lo que significa que amplía la lista de modo que «lista1» y «lista2» todavía tienen la referencia a la misma lista.
  • expresión lista1 = lista1 + [1, 2, 3, 4] crea una nueva lista y cambia la referencia «lista1» a esa nueva lista y «lista2» aún se refiere a la lista anterior.

Publicación traducida automáticamente

Artículo escrito por Kuldip Kumar 1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *