error :list out of range

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Nov 13 05:12:53 EST 2007


En Tue, 13 Nov 2007 06:23:02 -0300, Beema shafreen  
<beema.shafreen at gmail.com> escribió:

> for k in range(0,len(res_value),3):
>         check = res_value[k:k+4]
>         if check[0] < check[4]:
>                 print check
> error: File "app.py", line 16, in <module>
>     if check[0] < check[4]:
> IndexError: list index out of range
> i get an error like this how do i sort the error out to get result

Look at the exception: IndexError: list index out of range. That's pretty  
explicit: "some index" used as a subscript on "some list" is out of the  
allowed range. Most of the time, that means that the index is greater than  
or equal to the list length. Now look at the source line: if check[0] <  
check[4]. The possible out-of-range indexes are 0 and 4. 0 may be an  
invalid index when the list is empty; but the 4 is much more suspicious.  
We have to determine the length of the "check" list; that's easy looking  
one line above; res_value[k:k+4] has length 4. Valid indexes include 0, 1,  
2, and 3; 4 is an invalid index.

Now you should have enough info to fix your code. But, why use a flat  
list? Your data has certain structure, and you already read it line by  
line and use different variable names for each field. If you maintain that  
structure instead of flattening it into a list with anonymous elements,  
your code will be easier to write (and read, and understand).
Your file looks like a CSV file, and you could use the cvs module to read  
it. Let's read the file the same way you did, but using an object per row:

class ProbeData: # please choose a better name!
     "Holds current_span, probe, and length"

     def __init__(self, current_span, probe, length):
         self.current_span = current_span
         self.probe = probe
         self.length = length

     def __str__(self):
         return "%d %s %d" % (self.current_span, self.probe, self.length)

     __repr__ = __str__

dataset = []
fh = open('test','r')
for line in fh: # note that I've removed readlines()
         data = line.strip().split('\t')
         current_span = int(data[3].strip()) # assuming it's an integer
         probe = data[2].strip()
         length = int(data[4].strip()) # assuming it's an integer too
         probe_data = ProbeData(current_span, probe, length)
         dataset.append(probe_data)
fh.close()

for k in range(len(dataset)-1):
     this_probe = dataset[k]
     next_probe = dataset[k+1]
     if this_probe.current_span < next_probe.current_span:
         # Please check the condition above, it's just an example
         print this_probe

-- 
Gabriel Genellina




More information about the Python-list mailing list