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 aniterable
from left to right and returns the total.start
defaults to0
. The iterable's items are normally numbers, and thestart
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, seemath.fsum()
. To concatenate a series of iterables, consider usingitertools.chain()
.New in version 2.3.
Don't you think that start should be a number? Why can []
be written here?
(sum(a, []))
Python's built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.
Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.
1) Using sum() Method Python provides an inbuilt function called sum() which sums up the numbers in a list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With