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

前端 未结 3 1219
慢半拍i
慢半拍i 2020-12-20 23:09

Python not support adding a tuple to a list:

>>> [1,2,3] + (4,5,6)
Traceback (most recent call last):
  File \"\", line 1, in 

        
3条回答
  •  -上瘾入骨i
    2020-12-20 23:49

    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]
    

提交回复
热议问题