Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

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

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, [])
[1, 2, 3, 4, 5, 6]

I don't know what happened in these lines, and the documentation states:

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable's items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

New in version 2.3.

Don't you think that start should be a number? Why can [] be written here?

(sum(a, []))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 "<pyshell#2>", line 1, in <module>
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...