On Fri, Sep 19, 2008 at 3:09 PM, Stéfan van der Walt <[EMAIL PROTECTED]>wrote:

> 2008/9/19 mark <[EMAIL PROTECTED]>:
> > I need to multiply items in a list and need a list back. Which one of
> > the four options is best (I thought in Python there was only one way
> > to do something???)
>
> With the emphasis on "preferably" and "obvious" :)
>
> "There should be one-- and preferably only one --obvious way to do it."
>
> The modern idiom is the list comprehension, rather than the for-loop.
> Of those options,
> I personally prefer using "zip".
>
> >>>> [ x * y for x,y in zip(a,b) ]  # method 4
> > [10, 40, 90, 160]
>
> If you have very large arrays, you can also consider
>
> (np.array(x) * np.array(y)).tolist()
>
> Cheers
> Stéfan
> _______________________________________________
> Numpy-discussion mailing list
> [email protected]
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>

I think
[x*y for x in a for y in b]
feels pythonic, however it has a surprisingly lousy performance.

In [30]: %timeit [ x * y for x,y in zip(a,b) ]
100000 loops, best of 3: 3.96 µs per loop

In [31]: %timeit [ i*j for i in a for j in b ]
100000 loops, best of 3: 6.53 µs per loop

In [32]: a = range(100)

In [33]: b = range(100)

In [34]: %timeit [ x * y for x,y in zip(a,b) ]
10000 loops, best of 3: 51.9 µs per loop

In [35]: %timeit [ i*j for i in a for j in b ]
100 loops, best of 3: 2.78 ms per loop

Arnar
_______________________________________________
Numpy-discussion mailing list
[email protected]
http://projects.scipy.org/mailman/listinfo/numpy-discussion

Reply via email to