What does the built-in function sum do with sum(list, [])?

后端 未结 3 2067
梦谈多话
梦谈多话 2020-12-08 20:31

When I want to unfold a list, I found a way like below:

>>> a = [[1, 2], [3, 4], [5, 6]]
>>> a
[[1, 2], [3, 4], [5, 6]]
>>> sum(a,         


        
3条回答
  •  清歌不尽
    2020-12-08 20:46

    Don't you think that start should be a number?

    start is a number, by default; 0, per the documentation you've quoted. Hence when you do e.g.:

    sum((1, 2))
    

    it is evaluated as 0 + 1 + 2 and it equals 3 and everyone's happy. If you want to start from a different number, you can supply that instead:

    >>> sum((1, 2), 3)
    6
    

    So far, so good.


    However, there are other things you can use + on, like lists:

    >>> ['foo'] + ['bar']
    ['foo', 'bar']
    

    If you try to use sum for this, though, expecting the same result, you get a TypeError:

    >>> sum((['foo'], ['bar']))
    
    Traceback (most recent call last):
      File "", line 1, in 
        sum((['foo'], ['bar']))
    TypeError: unsupported operand type(s) for +: 'int' and 'list'
    

    because it's now doing 0 + ['foo'] + ['bar'].

    To fix this, you can supply your own start as [], so it becomes [] + ['foo'] + ['bar'] and all is good again. So to answer:

    Why [] can be written here?

    because although start defaults to a number, it doesn't have to be one; other things can be added too, and that comes in handy for things exactly like what you're currently doing.

提交回复
热议问题