最近,我注意到在连接列表时存在不一致性。
如果使用+运算符,则无法将列表与任何不同类型的对象连接起来。例如,
l = [1,2,3]
l = l + (4,5) #TypeError: can only concatenate list (not "tuple") to list
但是,如果我使用+=运算符,它会忽略对象的类型。例如:
l = [1,2,3]
l += "he" #Here, l becomes [1, 2, 3,"h", "e"]
l += (56, 67) #Here, l becomes [1, 2, 3,"h", "e", 56, 67]
那么,这只是语言的语义问题还是其他原因?
+
,则会存在关于结果类型的歧义。而使用+=
,则意味着左操作数决定了结果的类型。 - khelwood+=
for lists is more or less equivalent tolist.extend()
- Tomerikoo