How to initialize an array with a large number of members ?

Scott David Daniels Scott.Daniels at Acm.Org
Thu Jan 1 00:30:30 CET 2009


David Lemper wrote:
> ... Python. Using version 3.0
> # script23
> from array import array
>     < see failed initialization attempts  below >
>     tally = array('H',for i in range(75) : [0])
>     tally = array('H',[for i in range(75) : 0])
>     tally = array('H',range(75) : [0])
>     tally = array('H',range(75) [0])
>           Above give either Syntax error or TypeError
> 
>  All examples of sequences in docs show only a few members
>  being initialized. Array doc says an iterator can be used,
> but doesn't show how. 
First, [1,2,3] is iterable.  You could look up iterators or
generators or list comprehension, but since it's the holidays:
     import array
     tally = array.array('H', (0 for i in range(75)))# a generator
     tally = array.array('H', [0 for i in range(75)])# list comprehension

> What would you do for a 2 dimensional array ?  
You'll have to wait for numpy for the most general 2-D,
but for list-of-array:
     square = [array.array('H', (i * 100 + j for j in range(75)))
               for i in range(75)]
     square[4][8]



More information about the Python-list mailing list