# encoding=utf-8 a = ["a", "b", "c"] print "append|添加前id:%s" % id(a), a.append("d") print "添加後id:%s" % id(a), a print "-"*62 a = ["a", "b", "c"] print "extend|添加前id:%s" % id(a), a.extend("d") print "添加後id:%s" % id(a), a print "-"*62 a = ["a", "b", "c"] print " +|添加前id:%s" % id(a), a = a + ["d"] print "添加後id:%s" % id(a), a print "-"*62 a = ["a", "b", "c"] print " +=|添加前id:%s" % id(a), a += "d" print "添加後id:%s" % id(a), a
輸出結果:python
append|添加前id:40672072 添加後id:40672072 ['a', 'b', 'c', 'd']
--------------------------------------------------------------
extend|添加前id:40683080 添加後id:40683080 ['a', 'b', 'c', 'd']
--------------------------------------------------------------
+|添加前id:40672072 添加後id:40683208 ['a', 'b', 'c', 'd']
--------------------------------------------------------------
+=|添加前id:40672072 添加後id:40672072 ['a', 'b', 'c', 'd']app
能夠看出這四種方式均可以向列表中添加一個新元素,除了"+"以外,其餘三種方式都是在原列表上添加數據,"+"則會建立一個新的列表,而且"+"只能鏈接兩個列表,若是鏈接一個元素跟一個列表會報錯 spa
# encoding=utf-8 a = ["a", "b", "c"] print "append|添加前id:%s" % id(a), a.append(["d","e","f"]) print "添加後id:%s" % id(a), a print "-"*62 a = ["a", "b", "c"] print "extend|添加前id:%s" % id(a), a.extend(["d","e","f"]) print "添加後id:%s" % id(a), a print "-"*62 a = ["a", "b", "c"] print " +|添加前id:%s" % id(a), a = a + ["d","e","f"] print "添加後id:%s" % id(a), a print "-"*62 a = ["a", "b", "c"] print " +=|添加前id:%s" % id(a), a += ["d","e","f"] print "添加後id:%s" % id(a), a
輸出結果:code
append|添加前id:40082248 添加後id:40082248 ['a', 'b', 'c', ['d', 'e', 'f']]
--------------------------------------------------------------
extend|添加前id:40093384 添加後id:40093384 ['a', 'b', 'c', 'd', 'e', 'f']
--------------------------------------------------------------
+|添加前id:40082248 添加後id:40082376 ['a', 'b', 'c', 'd', 'e', 'f']
--------------------------------------------------------------
+=|添加前id:40082248 添加後id:40082248 ['a', 'b', 'c', 'd', 'e', 'f'] utf-8
append方法當添加的元素是列表時會回將整個列表添加進原列表,extend與"+="的效果是同樣的,會將列表中的元素添加到原列表,"+"也會將兩個列表中的元素複製到一個新建立的列表中,所不一樣的會建立一個新的列表 class