elementwise multiplication of 2 lists of numbers
Gary Herron
gherron at islandtraining.com
Mon Sep 20 16:26:36 CEST 2010
On 09/20/2010 07:02 AM, harryos wrote:
> hi
> 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,
> harry
>
List comprehension might be considered better by some, but that's a
subjective judgment. (One with which I agree.) List comprehension may
also be faster, but you'd have to test to know for sure.
>>> x=[2,4,3,1]
>>> y=[5,9,10,6]
>>> z = [a*b for a,b in zip(x,y)]
>>> print z
[10, 36, 30, 6]
Gary Herron
More information about the Python-list
mailing list