List += Tuple vs List = List + Tuple

╄→尐↘猪︶ㄣ 提交于 2019-12-28 06:40:09

问题


Let's say I have these assignments:

points = []
point = (1, 2)

How come when I do this:

points += point

It works completely fine, and gives me points = [1, 2]. However, If I do something like:

points = points + point

It gives me a TypeError: can only concatenate list (not "tuple") to list. Aren't these statements the same thing, though?


回答1:


The difference, is that list += is equivalent to list.extend(), which takes any iterable and extends the list, it works as a tuple is an iterable. (And extends the list in-place).

On the other hand, the second assigns a new list to points, and attempts to concatenate a list to a tuple, which isn't done as it's unclear what the expected results is (list or tuple?).



来源:https://stackoverflow.com/questions/13332987/list-tuple-vs-list-list-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!