Why can't I add a tuple to a list with the '+' operator in Python?

一世执手 提交于 2019-12-01 18:24:02

This is not supported because the + operator is supposed to be symmetric. What return type would you expect? The Python Zen includes the rule

In the face of ambiguity, refuse the temptation to guess.

The following works, though:

a = [1, 2, 3]
a += (4, 5, 6)

There is no ambiguity what type to use here.

Why python doesn't support adding different type: simple answer is that they are of different types, what if you try to add a iterable and expect a list out? I myself would like to return another iterable. Also consider ['a','b']+'cd' what should be the output? considering explicit is better than implicit all such implicit conversions are disallowed.

To overcome this limitation use extend method of list to add any iterable e.g.

l = [1,2,3]
l.extend((4,5,6))

If you have to add many list/tuples write a function

def adder(*iterables):
    l = []
    for i in iterables:
        l.extend(i)
    return l

print adder([1,2,3], (3,4,5), range(6,10))

output:

[1, 2, 3, 3, 4, 5, 6, 7, 8, 9]

You can use the += operator, if that helps:

>>> x = [1,2,3]
>>> x += (1,2,3)
>>> x
[1, 2, 3, 1, 2, 3]

You can also use the list constructor explicitly, but like you mentioned, readability might suffer:

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