[Tutor] Array indexing

Dave Kuhlman dkuhlman at rexx.com
Tue Jan 16 18:55:27 CET 2007


On Tue, Jan 16, 2007 at 11:28:49AM -0500, Joe Abbey wrote:
> Hello,
> 
> I'm using Active Python v2.4.3.11 on a Windows XP machine.
> 
> Probably more relevant is that I'm just learning Python, as in I've been
> writing Python for less than 24 hours.
> 
> While trying to implement a PE parser, I ran into the following problem:
> 
> #************** START CODE*******************
> data = file.read(128);
> directoryTable = struct.unpack('LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', data);
> i=0;
> print "Export table           0x%08X + 0x%08x" % (directoryTable[i+=1],
> directoryTable[i+=1]);
> print "Import table           0x%08X + 0x%08x" % (directoryTable[i+=1],
> directoryTable[i+=1]);
> #************** END CODE*******************
> 
> This code throws a syntax error at the first i+=1 on "line 4".
> 
> Why is this the case?
> 

In Python, "i += 1" is a statement.  You have used in as an
expression.  In Python, an expression returns a value; a statement
does not.

> It seems like it would be very useful to be able to increment an index after
> referencing into an array.
> 

What you are asking for is viewed by some as useful.  But, I think
it is too confusing.  Should the variable be incremented before or
after it is used to index into the array?  C/C++ gives you a
choice: you can use either "i++" or "++i", which makes code harder
to read, I think.  And, what about:

    x = y[i+=1] + z[i]

Has the second use of "i" been incremented or not.

> Is my approach busted?  Is there a better way to reference elements?
> 

Instead of:

    x = directoryTable[i] + directoryTable[i+=1]);

use something like:

    x = directoryTable[i] + directoryTable[i+1]

And, by the way, you do not need all those semicolons at the end of
each line.  In Python, the semicolon is a statement separator, not
a statement terminator.  It is more Pythonic to use a semicolon
between statements only when there are more than one statement on a
line.  And writing more than one statement on a line is usually
discouraged anyway.

> The "fix" I'm currently using is to write the index I want:
> 
> (directoryTable[0], directoryTable[1])

Or, if you need an index variable:

    directoryTable[i], directoryTable[i+1])

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list