注意+=和append()的效果一样, 以及和list=list+[6,7]区别

# What is the difference between these two pieces of code?
list1 = [1,2,3,4,5]
list2 = [1,2,3,4,5]

def proc(mylist):
    mylist=mylist+[6,7]

def proc2(mylist):
    mylist.append(6)
    mylist.append(7)

# Can you explain the results given by the print statements below?

print "demonstrating proc"
print list1
proc(list1)
print list1
print
print "demonstrating proc2"
print list2
proc2(list2)
print list2

'''
demonstrating proc
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
demonstrating proc2
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7]
'''

# Python has a special assignment syntax: +=.  Here is an example:

list3 = [1,2,3,4,5]
list3 += [6, 7]

# Does this behave like list1 = list1 + [6,7] or list2.append([6,7])? Write a
# procedure, proc3 similar to proc and proc2, but for +=. 

def proc3(mylist):
    mylist += [6,7]

list4 = [1,2,3,4,5]
proc3(list4)

#>>> list4
#>>> [1, 2, 3, 4, 5, 6, 7]
#注意,调用 proc3(list4) 后,现在 list4 附加了元素 [6,7],和 proc2 一样。因此,我们发现使用 += 和向变量添加值(append)一样。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值