[Numpy-discussion] which one is best?

Stéfan van der Walt stefan@sun.ac...
Fri Sep 19 08:09:00 CDT 2008

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()


More information about the Numpy-discussion mailing list