Iteration over two sequences

Henrik Holm news+0409 at
Wed Jan 12 10:54:12 EST 2005

I am just starting to learn Python, mostly by going through the examples
in Dive Into Python and by playing around.

Quite frequently, I find the need to iterate over two sequences at the
same time, and I have a bit of a hard time finding a way to do this in a
"pythonic" fashion.  One example is a dot product.  The straight-ahead
C-like way of doing it would be:

def dotproduct(a, b):
    psum = 0
    for i in range(len(a)):
        psum += a[i]*b[i]
    return psum

However, the range(len(a)) term is awfully un-pythonic :)
The built-in function map() gives me a way of "transposing" the a list
and the b list, and  now I can handle it with a list comprehension:

def dotproduct(a, b):
    return sum([x*y for x, y in map(None, a, b)])

My concern is one of efficiency: it seems to me that I have two loops
there: first one implied with map(...) and then the for loop -- which
seems like a waste since I feel I should be able to do the
multiplication via an argument to map.  So far I have come up with an
alternative via defining a separate function:

def dotproduct(a, b):
    def prod(x,y): return x*y
    return sum(map(prod, a, b))

I suppose I could also use a lambda here -- but is there a different,
efficient, and obvious solution that I'm overlooking?


"On some great and glorious day the plain folks of the land will reach
in their heart's desire at last and the White House will be adorned by
a downright moron."
                             -H.L. Mencken (1880-1956) American Writer 

More information about the Python-list mailing list