sum
!I realized that I could write smartly if I thought that there was only a delicate way to do it.
Python supports addition between lists,
[1,2,3] + [4,5,6] => [1,2,3,4,5,6]
Utilizing the fact that the sum function can specify the initial value as the second argument,
data = [[1,2,3], [4,5,6], [7,8,9]]
sum(data, [])
You can write like this.
That said, it's a bit inflexible that tuples and generators aren't supported unless it's a list.
In python3 series, sum seems to check the type, so this method cannot be used. Remorse.
By using this, I wondered if it would be possible to process all instances that implement __add__
with sum.
>>> a = [1,2,3]
>>> data = [a, [4,5,6], [7,8,9]]
>>> sum(data,[])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a
[1, 2, 3]
>>> empty = []
>>> sum(data,empty)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> empty
[]
>>>
Internally, it is expected that the result of addition is used for processing.
So, if you pass a class with __add__
as shown below,
>>> class A:
... def __add__(self, target):
... self.target = target
... return 100
...
>>> a = A()
>>> sum([5,10,15,20],a)
145
>>> a.target
5
... Well, I understand that you shouldn't make __add__
a destructive implementation.
Recommended Posts