zip list, variables

Jussi Piitulainen jpiitula at ling.helsinki.fi
Wed Nov 20 05:45:58 EST 2013


flebber <flebber.crue at gmail.com> writes:

> 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'

The error message comes from sum(([1,2],[5,6])), where start defaults
to 0. A way to understand what is happening is to inspect zip(a,b),
notice that the first element of zip(a,b) is ([1,2],[5,6]), and then
find out what sum(([1,2],[5,6])) is. The extra parentheses may seem a
bit subtle, and at least in Python 3, zip and map return opaque
objects, so it does take a bit to get used to all the details,

The offending operands to '+' are 0 and [1,2].

> How can I do this legally?

I think the easiest is [ x + y for x, y in zip(a,b) ] if you want
concatenation, and something like the following if you want a nested
numerical addition:

  >>> [ [ x + y for x, y in zip(x,y) ] for x, y in zip(a,b) ]
  [[6, 8], [10, 12]]

There is probably a way to use map and sum for this, together with the
mechanisms that change arguments to lists or vice versa (the syntax
involves *), and partial application to specify a different start for
sum if you want concatenation, but I doubt you can avoid some sort of
nesting in the expression, and I doubt it will be clearer than the
above suggestions. But someone may well show a way. (Sorry if this
paragraph sounds like so much gibberish.)



More information about the Python-list mailing list