Advantage of the array module over lists?

Michael Wieher michael.wieher at gmail.com
Sun Mar 16 15:12:24 CET 2008


I believe the array module provides more functionality than lists.
Perhaps this extra functionality comes with... overhead?  C'est possible.
For example, you can declare an array to contain all items of a type, ie:

>>array.array('f')    #array of floats

So, they might be efficient, in that they're more efficient than wrapping
lists on your own, if you *need* the extra power they provide.
Not sure.


2008/3/16, Arnaud Delobelle <arnodel at googlemail.com>:
>
> Tobiah <toby at tobiah.org> writes:
>
> > I checked out the array module today.  It claims that
> > arrays are 'efficient'.  I figured that this must mean
> > that they are faster than lists, but this doesn't seem
> > to be the case:
> >
> > ################ one.py ##############
> > import array
> >
> > a = array.array('i')
> >
> > for x in xrange(10000000):
> >         a.append(x)
> >
> > for x in a:
> >         a[x] += 1
> >
> > ################ two.py ##############
> > a = []
> >
> > for x in xrange(10000000):
> >         a.append(x)
> >
> > for x in a:
> >         a[x] += 1
> >
> > ######################################
> >
> >
> > ktops:toby:pytest> time python one.py; time python two.py
> >
> > real    0m28.116s
> > user    0m17.504s
> > sys     0m10.435s
> >
> > real    0m23.026s
> > user    0m13.027s
> > sys     0m9.777s
> >
> >
> > Perhaps the only advantage is that they take less memory
> > to store a large number of items?  It would seem then, that
> > 'economical' might have been a better choice of word than
> > 'efficient'.
>
> I get an even bigger difference with this test (same as yours, but
> using timeit and using an allegedly more efficient way of initialising
> the array)
>
> >>> def test(arr, n):
> ...     a = arr(xrange(n))
> ...     for x in a:
> ...         a[x] += 1
> ...
> >>> n = 10000000
> >>> import timeit
> >>> timeit.Timer('test(list, n)', 'from __main__ import test,
> n').timeit(1)
> 2.4988760948181152
> >>> from array import array
> >>> arr = lambda n: array('i', n)
> >>> timeit.Timer('test(arr, n)', 'from __main__ import test, arr,
> n').timeit(1)
> 5.7419960498809814
> >>>
>
> --
> Arnaud
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080316/d3fafa56/attachment.html>


More information about the Python-list mailing list