[Tutor] Array

Jeff Shannon jeff@ccvcorp.com
Wed Jan 29 13:17:05 2003


Denis Hanley wrote:

> what I need to do is create an Array.  Input Information into the 
> Array on the fly and then output my data in this format:
>  
> LineData = array[x1 y1, x2 y2, x3 y3, etc]
>  
> Line x1 y1  x2 y2
> Line x2 y2 x3 y3
> Line x3 y3 x4 y4


What other languages do with Arrays, Python typically does with lists. 
 (There's some differences, and Python does actually have an Array 
module, but a list is usually the best translation.)

It looks like in each 'slot' in your list, you have an (x,y) coordinate 
pair.  The Python structure to use for this would typically be a tuple. 
 So you would have a list of 2-element tuples as your basic data structure.

LineData = [ (x1,y1), (x2,y2), (x3,y3), (x4,y4) ]

Now, you want to proceed through that list, showing tuples in pairs.  A 
normal for loop in Python will iterate over a sequence one-at-a-time, 
but that's not quite what we want.  We need the index that we're at, so 
that we can also get the *next* element of the list -- each iteration, 
we want to show element N and element N+1.  This means that we're going 
to iterate len(LineData) - 1 times, because the last element won't have 
a next element to pair with.  

We can use the range() function to generate a sequence of indexes 
that'll fit our needs, and then use a for loop to iterate over that 
sequence of indexes.  Lists start indexing at 0, and range() defaults to 
starting its generated sequence at 0, so that works out very 
conveniently.  Let's try it out.

 >>> LineData = [ (1,2), (3,4), (5,6), (7,8), (9,0) ]
 >>> for n in range( len(LineData)-1 ):
...     print "Line %d:  %s  %s" % (n+1, LineData[n], LineData[n+1])
...
Line 1:  (1, 2)  (3, 4)
Line 2:  (3, 4)  (5, 6)
Line 3:  (5, 6)  (7, 8)
Line 4:  (7, 8)  (9, 0)
 >>>

Hope this helps!

Jeff Shannon
Technician/Programmer
Credit International