zip list, variables

Peter Otten __peter__ at web.de
Wed Nov 20 05:38:36 EST 2013


flebber wrote:

> If
> 
> c = map(sum, zip([1, 2, 3], [4, 5, 6]))
> 
> c
> Out[7]: [5, 7, 9]
> 
> why then can't I do this?
> 
> a = ([1, 2], [3, 4])
> 
> b = ([5, 6], [7, 8])
> 
> c = map(sum, zip(a, b))
> 
---------------------------------------------------------------------------
> TypeError                                 Traceback (most recent call
> last) <ipython-input-3-cc046c85514b> in <module>()
> ----> 1 c = map(sum, zip(a, b))
> 
> TypeError: unsupported operand type(s) for +: 'int' and 'list'
> 
> How can I do this legally?

You are obscuring the issue with your map-zippery. The initial value of 
sum() is 0, so if you want to "sum" lists you have to provide a start value, 
typically an empty list:

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

Applying that to your example:

>>> def list_sum(items):
...     return sum(items, [])
... 
>>> map(list_sum, zip(a, b))
[[1, 2, 5, 6], [3, 4, 7, 8]]

Alternatively, reduce() does not require an initial value:

>>> map(functools.partial(reduce, operator.add), zip(a, b))
[[1, 2, 5, 6], [3, 4, 7, 8]]

But doing it with a list comprehension is the most pythonic solution here...




More information about the Python-list mailing list