Diez B. Roggisch
deets at nospam.web.de
Mon May 1 17:48:11 CEST 2006
> There must be a better way to multiply the elements of one list by
> a = [1,2,3]
> b = [1,2,3]
> c = 
> for i in range(len(a)):
> a = c
> print a
> [1, 4, 9]
> Perhaps a list comprehension or is this better addressed by NumPy?
First of all: it's considered bad style to use range if all you want is a
enumeration of indices, as it will actually create a list of the size you
specified. Use xrange in such cases.
You can use a listcomp like this:
c = [a[i] * b[i] for i in xrange(len(a))]
But maybe nicer is zip:
c = [av * bv for av, bv in zip(a, b)]
And if lists get large and perhaps multidemnsional, numpy certainly is the
way to go.
More information about the Python-list