elementwise multiplication of 2 lists of numbers

Peter Otten __peter__ at web.de
Mon Sep 20 12:33:30 EDT 2010


harryos wrote:

> I have 2 lists of numbers,say
> x=[2,4,3,1]
> y=[5,9,10,6]
> I need to create another list containing
> z=[2*5, 4*9, 3*10, 1*6]  ie =[10,36,30,6]
> 
> I did not want to use numpy or any Array types.I tried to implement
> this in python .I tried the following
> 
> z=[]
> for a,b in zip(x,y):
>         z.append(a*b)
> This gives me the correct result.Still,Is this the correct way?
> Or can this be done in a better way?
> 
> Any pointers most welcome,

Finally, if you have a lot of data that you want to process efficiently 
consider using numpy arrays instead of lists:

>>> import numpy
>>> x = numpy.array([2,4,3,1])
>>> y = numpy.array([5,9,10,6])
>>> x*y
array([10, 36, 30,  6])

Peter



More information about the Python-list mailing list