[Tutor] Arrays and tuples

Magnus Lycka magnus@thinkware.se
Mon Jan 27 17:50:02 2003


At 15:32 2003-01-27 +0000, Deirdre Hackett wrote:
>I want to now put my 3 integer values into an array but it will not let me do
>
>data[0] = int(x2string)
>data[1] = int(y2string).... etc

As others have told you, the typical Python structure to
use when arrays are used in other languages is a list. But
while
   l = []; l.append(x); l.append(y)
is certainly a common construct, you can also initialize
with values, which you tried to do...

>instead I have to
>data = (int(x2string), int(y2string), int(z2string))

You are so close here. Just use [] instead of the outer
().

t = (1, 2)
l = [1, 2]
d = {1: 2, 'a':'b'}

Here, t is a tuple, l is a list, and d is a dictionary.
As you noted, tuples are immutable. Dictionaries differ
from lists and tuples in that they have arbitrary (well
almost) keys.

In this case, both t[1], l[1] and d[1] will return the
same value: 2. Now you might understand why you could
not simply do:

data[0] = something

There is no way for python to know whether you are trying
to put something into a list or a dictionary here. Actually,
there are a number of other types of objects as well, which
use the x[n] notation.

Anyway, there IS actually an array type in python as well.
It's helpful if you want to restrict a list-like object to
certain types of values.

 >>> import array
 >>> help(array)

...

 >>> a = array.array('i')
 >>> type(a)
<type 'array.array'>
 >>> a.append(1)
 >>> a.append(2)
 >>> a.append('r')
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: an integer is required
 >>> print a
array('i', [1, 2])
 >>> for i in a:
...     print i
...
1
2
 >>> a = array.array('f')
 >>> a.append(1)
 >>> a.append(2)
 >>> a.append('r')
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: bad argument type for built-in operation
 >>> print a
array('f', [1.0, 2.0])
 >>> for i in a:
...     print i
...
1.0
2.0

But just as with lists, you must use append (or insert etc) to make
it bigger, you can't do this:

 >>> a[2] = 7
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
IndexError: array assignment index out of range


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se