Parallel arithmetic?

Michael Hoffman cam.ac.uk at mh391.invalid
Thu Aug 4 19:01:13 EDT 2005


Terrance N. Phillip wrote:
> Given a and b, two equal length lists of integers, I want c to be 
> [a1-b1, a2-b2, ... , an-bn]. I can do something like:
> 
> c = [0] * len(a)
> for ndx, item in enumerate(a):
>     c[ndx] = item - b[ndx]
> 
> But I'm wondering if there's a better way, perhaps that avoids a loop?

Here's one way:

c = [a_item - b_item for a_item, b_item in zip(a, b)]

And another:

import operator
c = map(operator.sub, a, b)
-- 
Michael Hoffman



More information about the Python-list mailing list