Lists

Jason Stokes jstok at bluedog.apana.org.au
Tue Apr 18 18:41:56 CEST 2000


Daley, MarkX wrote in message ...
>This feels like a real newbie question, but here is the code that is
causing
>my question:
>
># Learning exceptions
>
>def test():
>    a = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
>    print a
>    b = 5
>    for item in a:
>       try:
>           print b / a[item]
>       except ZeroDivisionError:
>           pass


Firstly, please retain correct indenting when posting code snippets.
Indenting is significant in Python.  I've corrected it for you.

>Why is the list being processed in reverse?  The exception works fine, but
>the math is backwards.  I don't recall this happening before.


Iteration one binds to the name item the first element of a, which happens
to be -5.

You then try to divide b by a[item], which is a indexed by -5.  Negative
indexes are legal in python and the effect is to return a reference to the
fifth element from the *right*.

In short, you've misapplied "for item in a" construct, which is very
different from the C construct.  In Python it repeatedly binds the name
"item" to the next element of list "a", does the sub-block, then repeats
until there's no longer any elements left in a.   You don't need to index a.
To do that, you'd do:

for i in range(0...len(a)):
   try:
       print b / a[i]
   except ZeroDivisionError:
      pass

But this will mark you with the stigma of a programmer hankering for his old
C days.... what you needed to write was merely:

for item in a:
   try:
       print b / item
   except ZeroDivisionError:
      pass

Cheers,
Jason Stokes: jstok at bluedog.apana.org.au





More information about the Python-list mailing list