"Rehceb Rotkiv" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] |I want to check whether, for example, the element myList[-3] exists. So | far I did it like this: | | index = -3 | if len(myList) >= abs(index): | print myList[index] # Note that tabs gets lost in some newsreaders. Spaces are better for posting
A full test of the index, equivalent to the try below, is as follows: n = len(myList) if -n <= index < n # same as <= n-1, but avoids subtraction This works for empty lists also (-0 <= i < 0 is never true!). | Another idea I had was to (ab-?)use the try...except structure: | | index = -3 | try: | print myList[index] | except: | print "Does not exist!" Follow Gary Herron's comment on this. | Is it ok to use try...except for the test Both idioms are acceptible. Some people would chose based on whether they expect bad indexes to be a normal occurence or an exceptional occurrence. One rule-of-thumb division point is 10% frequency. More expensive tests would push this higher. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list