[Numpy-discussion] which one is best?

Arnar Flatberg arnar.flatberg@gmail....
Fri Sep 19 08:50:49 CDT 2008


On Fri, Sep 19, 2008 at 3:09 PM, Stéfan van der Walt <stefan@sun.ac.za>wrote:

> 2008/9/19 mark <markbak@gmail.com>:
> > 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
> Numpy-discussion@scipy.org
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080919/1bd977e2/attachment.html 


More information about the Numpy-discussion mailing list