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

后端 未结 3 2043
梦谈多话
梦谈多话 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:51

    You sum the start with the contents of the iterable you provide as the first argument. sum doesn't restrict the type of start to an int in order to allow for various cases of adding.

    Essentially sum does something like this:

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

    Roughly translates to:

    number += every value in the list a
    

    Since every value in the list a is a list this works and the previous summation, when expanded, looks like this:

    number + [1, 2] + [3, 4] + [5, 6]
    

    So if you enter an int this will result in an unfortunate TypeError because adding an int and a list is not allowed.

    1 + [1, 2] == I hope you like TypeErrors
    

    However, If you enter a list [] it is simply going to join the elements of a together and result in the flattened list we know and love.

    The value of start defaults to 0 an int mainly because the most common case of summation is arithmetic.

提交回复
热议问题