[Numpy-discussion] appending extra items to arrays

Mark Janikas mjanikas@esri....
Thu Oct 11 11:42:02 CDT 2007


If you do not know the size of your array before you finalize it, then
you should use lists whenever you can.  I just cooked up a short
example:

######################################################################
import timeit
import numpy as N

values = range(10000)

def appendArray(values):
    result = N.array([], dtype="int")
    for value in values:
        result = N.append(result, value)
    return result

def appendList(values):
    result = []
    for value in values:
        result.append(value)
    return N.array(result)

test = timeit.Timer('appendArray(values)',
        'from __main__ import appendArray, values')
t1 = test.timeit(number=10)

test2 = timeit.Timer('appendList(values)',
        'from __main__ import appendList, values')
t2 = test2.timeit(number=10)

print "Total Time with array: " + str(t1)
print "Total Time with list: " + str(t2)

##### Result #####
Total Time with array: 2.12951189331
Total Time with list: 0.0469707035741
########################################################################
####

Hope this helps,

MJ

-----Original Message-----
From: numpy-discussion-bounces@scipy.org
[mailto:numpy-discussion-bounces@scipy.org] On Behalf Of Adam Mercer
Sent: Thursday, October 11, 2007 7:42 AM
To: Discussion of Numerical Python
Subject: Re: [Numpy-discussion] appending extra items to arrays

On 11/10/2007, Robert Kern <robert.kern@gmail.com> wrote:

> Appending to a list then converting the list to an array is the most
> straightforward way to do it. If the performance of this isn't a
problem, I
> recommend leaving it alone.

Thanks, I'll leave it as is - I was just wondering if there was a
better way to do it.

Cheers

Adam
_______________________________________________
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion



More information about the Numpy-discussion mailing list