Python "why" questions

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat Aug 21 02:26:19 CEST 2010


Martin Gregorie wrote:
> On Mon, 16 Aug 2010 12:33:51 +1200, Gregory Ewing wrote:
> 
> 
>>Ian Kelly wrote:
>>
>>>On Fri, Aug 13, 2010 at 11:53 AM, Martin Gregorie
>>><martin at address-in-sig.invalid> wrote:
>>
>>>>      real sample[-500:750];
>>
>>>Ugh, no.  The ability to change the minimum index is evil.
>>
>>Not always; it can have its uses, particularly when you're using the
>>array as a mapping rather than a collection.
>>
> 
> Say you have intensity data captured from an X-ray goniometer from 160 
> degrees to 30 degrees at 0.01 degree resolution. Which is most evil of 
> the following?
> 
> 1) real intensity[16000:3000]
>    for i from lwb intensity to upb intensity
>       plot(i/100, intensity[i]);
> 
> 2) double angle[13000];
>    double intensity[13000];
>    for (int i = 0; i < 13000; i++)
> 	plot(angle[i], intensity[i]);
> 
> 3) struct 
>    { 
>       double angle;
>       double intensity 
>    } measurement;
>    measurement m[13000];
>    for (int i = 0; i < 13000; i++)
> 	plot(m[i].angle, m[i].intensity);
> 
> 4) double intensity[13000];
>    for (int i = 0; i < 13000; i++)
>       plot((16000 - i)/100, intensity[i])
>  
> To my mind (1) is much clearer to read and far less error-prone to write, 
> while zero-based indexing forces you to use code like (2), (3) or (4), 
> all of which obscure rather than clarify what the program is doing.

This might be true if the only thing you ever do with your
indices is use them to iterate over the array. However, if
you need to do any arithmetic with them, you may find yourself
thinking again.

Also, in Python you wouldn't write iteration loops that way
in the first place. You would write things such as

   for x, y in zip(angle, intensity):
     plot(x, y)

which avoids dealing with indexes altogether. The only time
you really need to use indexes in Python is when you want to
do arithmetic with them, or take slices, both of which turn
out to be less confusing most of the time with 0-based indexing.

-- 
Greg





More information about the Python-list mailing list