[Tutor] Arrays and tuples

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon Jan 27 13:54:01 2003


On Mon, 27 Jan 2003, 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
>
> instead I have to
> data = (int(x2string), int(y2string), int(z2string))
>
> and this is only a tuple in which the size cannot be changed.
>
> Can you create an array that you can append values to it. You cannot
> append vales to a tuple - its size is static.

Instead of using a tuple, you may want to use a Python list: unlike a
traditional array, it can expand as long as we tell it to.

###
>>> people = []
>>> people.append('gamma')
>>> people.append('helm')
>>> people
['gamma', 'helm']
>>> people.append('johnson')
>>> people.append('vissides')
>>> people
['gamma', 'helm', 'johnson', 'vissides']
>>> people.pop(-1)
'vissides'
>>> people
['gamma', 'helm', 'johnson']
###

The session above shows that we can even 'pop()' off pieces out of our
list if we want.  We can learn more about lists by looking at:

http://www.python.org/doc/tut/node7.html#SECTION007100000000000000000


By the way, you might want to be careful about the word "array": arrays
are traditionally used to say that we want a container of fixed size, so
"appending to an array" is an oxymoron in certain circumstances.  *grin*


Good luck!