简体   繁体   中英

List += Tuple vs List = List + Tuple

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?

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?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM