Newbie: How do I implement an 2 element integer array in Python.?

Steve Holden sholden at holdenweb.com
Wed Oct 11 10:37:38 EDT 2000


jbranthoover at my-deja.com wrote:
> 
> Hello All,
>         What is the syntax for creating a 2 element integer array?  I
> have looked at the Array  Module documentation,  but I am afraid that I
> don’t quite understand it.  In Basic I would do something like:
> 
> Dim     MyArray(100,16)
> 
Well, forst of all, a two-element array would be declared as

Dim MyArray(2)

What you want is a two-dimensional array!

> For i = 0 to 100
>         For j = 0 to 16
>               MyArray( i,j ) = MyData
>         Next j
> Next i
> 
>         Can someone out there give me a quick example of how this
> function is done in Python?  Thank you for you time and have a nice day.
> 

A simple approach would be:

twod = []			# construct empty list
for i in range(100):		# for each row
    twod.append([])		# append an empty column list
    for j in range(16):		# for each column
	twod[i].append(myData)	# append data for this row/column

However, your elements would have to be accessed as

	twod[row][col]

Builtin functions to construct empty lists of arbitrary size might
save time, space and garbage collection, but a recent discussion
explained that

twod = [ ([[]] * 16) ] * 100

would not work.  Essentially, elements end up pointing to the
same data item, and changing an element changes other elements!

>>> arr = [ ([[]] * 2) ] * 3
>>> arr
[[[], []], [[], []], [[], []]]
>>> arr[0][0] = "spam"
>>> arr
[['spam', []], ['spam', []], ['spam', []]]

regards
 Steve
-- 
Helping people meet their information needs with training and technology.
703 967 0887      sholden at bellatlantic.net      http://www.holdenweb.com/





More information about the Python-list mailing list