Python--x += y和x = x + y的区别

一.对于不可变类型(string, int, tupe),两种方法相等,都改变了原来的值,生成了新的对象

>>> n1 = 1
>>> id(n1)  
1936485392
>>> n1 = n1 + 1 
>>> n1  
2
>>> id(n1)
1936485424
>>> 
>>> n2 = 1
>>> id(n2)
1936485392
>>> n2 += 2
>>> id(n2)
1936485456

二.对于可变对象(list, dict),两种方法有差别,x += y没有产生新对象,x = x +y 产生了新对象

>>> list1 = [1 ,2]       
>>> id(list1)    
2787361876040
>>> list2 = [3, 4]      
>>> list1 += list2      
>>> list1       
[1, 2, 3, 4]
>>> id(list1) 
2787361876040       # 对象id没有发生变化
>>> 
>>> list3 = [1, 2]
>>> id(list3)   
2787361653000
>>> list3 = list3 + list2
>>> list3   
[1, 2, 3, 4]
>>> id(list3)
2787361755464       # 对象id发生了变化

需要注意在函数中使用不同运算符的时候,会导致不同结果的陷阱

>>> def add_num1(n):
       n += n

>>> list1 = [1, 2]    
>>> id(list1)     
2787361757384
>>> add_num1(list1)      
>>> list1      
[1, 2, 1, 2]         # 作为参数的变量的值被改变了
>>>     
>>> def add_num2(n):
       n = n + n

>>> list1 = [1, 2]    
>>> add_num2(list1)       
>>> list1      
[1, 2]               # 作为参数的变量的值没有被改变
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值