indexerror: list index out of range??

Dave Angel davea at davea.name
Fri Jun 28 21:58:09 EDT 2013


On 06/28/2013 09:20 PM, Titiksha Joshi wrote:
> Hi,
> I am working on the following code but am getting the error: list index out of range. I surfed through the group but somehow I am not able to fix my error.Please guide.Structure is given below:
> m is a list of 5 elements. I have to match elements of m from fields in file ALL_BUSES_FINAL.cvs.
> m=['631138', '601034', '2834', '2908', '64808']
>

It's not hard to see what's wrong in the following excerpt, but it is 
hard to guess what you really wanted.

Did you want to find all lines which match any of the strings in m?  Or 
are you just satisfied to match each of the strings in m against *some* 
line of the file?  Or is it something else entirely?

You have a nested loop here (for loop inside a while loop), and you're 
confusing the limit values for the outer one.

> i=0
> while i<len(m):
>      print(i)
>      my_file = open("ALL_BUSES_FINAL.csv", "r+")
>      for line in my_file:
>          if m[i] in line:
>              print (line)
>              a.append(line)
>              i+=1

You increment i here, but do not check if it's reached the end of the m. 
  So eventually it does, and crashes.

>              print(a)
>      my_file.close()
>
>
> The output is as follows:
> 0
> LAKEFLD  3227,631138
>
> ['LAKEFLD  3227,631138\n']
>
> 1
> NOBLES   3013,601034
>
> ['LAKEFLD  3227,631138\n', 'NOBLES   3013,601034\n']
>
> 2
> GR_ISLD  I,2834
>
> ['LAKEFLD  3227,631138\n', 'NOBLES   3013,601034\n', 'GR_ISLD  I,2834\n']
>
> FTTHOMP  928,2908
>
> ['LAKEFLD  3227,631138\n', 'NOBLES   3013,601034\n', 'GR_ISLD  I,2834\n', 'FTTHOMP  928,2908\n']
>
> VICTRYH  15,64808
>
> ['LAKEFLD  3227,631138\n', 'NOBLES   3013,601034\n', 'GR_ISLD  I,2834\n', 'FTTHOMP  928,2908\n', 'VICTRYH  15,64808\n']
> Traceback (most recent call last):
>    File "C:\Users\TJ\dist_tracking.py", line 40, in <module>
>      if m[i] in line:
> IndexError: list index out of range
>>>>
>
> I see the line,a being correct but print (i) does not show up after 2. and index error comes up. I am too confused now. Please guide.
> Thanks in advance.
>

Another big problem will arise as soon as you have a string in m which 
is a strict substring of a value in the line.  You'll get false matches. 
  So presumably you really want to use csv logic, and have explicit 
fields that you're searching for, rather than using 'in' operator.  And 
at that point, maybe you just want to check field #2 of each line.


-- 
DaveA



More information about the Python-list mailing list