[Numpy-discussion] when and where to use numpy arrays vs nested lists
Travis Oliphant
oliphant at ee.byu.edu
Thu Mar 1 12:25:45 EST 2007
Mark P. Miller wrote:
>I've been using Numpy arrays for some work recently. Just for fun, I
>compared some "representative" code using Numpy arrays and an object
>comprised of nested lists to represent my arrays. To my surprise, the
>array of nested lists outperformed Numpy in this particular application
>(in my actual code by 10%, results below are more dramatic).
>
>Can anyone shed some insight here? The functions that I use in reality
>are much more complicated than those listed below, but they are
>nonetheless representative of the type of thing that I'm doing.
>
>
>##imports
>import numpy as NP
>from numpy.random import randint
>
>#numpy array code
>array1 = NP.zeros((50,50), int)
>
>def random1():
> c = array1(randint(10), randint(10))
>
>
Is this a bug? You can't "call" an array. Did you mean,
array1[randint(10), randint(10)]?
Getting single indices like this is a bit slower for NumPy then for
lists because of all the possibilities that must be distinguished for
array indexing. List indexing is a very simple thing. Thus, lists can
be seen as collections that are optimized for simple indexing. If all
you are doing is simple indexing, then lists are going to be faster.
You can try using array1.item(randint(10), randint(10)), like this:
getitem = array1.item
def random1():
getitem(randint(50), randint(50))
Also, you might try using
array2 = array1.tolist()
instead of creating one like you do.
I get comparable speeds in this case.
More information about the NumPy-Discussion
mailing list