#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Posts
    23
    Rep Power
    0

    How do I defeat the Index out of range error


    Hello,

    I am working with the pyAmazon module to download Product Information from Amazon. I am having problems determining the highest item number. I keep trying higher index numbers until I get a traceback error.
    What is the best way to trap the error to get the last item in the index? I know this sounds like a stupid question, but I am new to Python and am not sure about the best way to handle this. Here is how I get the error.
    Code:
    
    >>> Results = amazon.searchByKeyword('"python in a nutshell"', product_line="books", type="heavy", page=1, license_key=None, http_proxy=None, locale=None, associate=None)
    
    >>> Results[0].URL
    u'http://www.amazon.com/exec/obidos/ASIN/0596001886/auctiotechnos-20?dev-t=D1O8SL0D5PWXV%26camp=2025%26link_code=xm2'
    
    >>> Results[1].URL
    Traceback (most recent call last):
      File "<pyshell#38>", line 1, in -toplevel-
        Results[1].URL
    IndexError: list index out of range
    >>>
    Thanks,
    Chuck
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,643
    Rep Power
    4247
    Why not just do a len(Results) which will let you know how many items are in your array. Remember that the array is 0-based, which means the return value of len is 1 greater than your max index value.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Posts
    23
    Rep Power
    0

    Worked perfectly


    Thanks Scorpions!

    I can't believe I did not think of that!

    Chuck
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Depending on how you mean defeat, you could use a try-except block to catch the error before it escapes and your program burns.

    Code:
    try:
        …whatever using an index…
    except IndexError:
        …Deal with the index error…
    Though its even better if you can stop the error before it even starts - as Scorpy explained .

    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo