indexerror: list index out of range??

Chris Angelico rosuav at gmail.com
Fri Jun 28 21:53:51 EDT 2013


On Sat, Jun 29, 2013 at 11:20 AM, Titiksha Joshi
<joshi.titiksha90 at gmail.com> 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']
>
> 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
>             print(a)
>     my_file.close()

What this does is open the file once for every string in 'm', and read
through it. But you increment i for every line in the file, that's why
you're having problems.

I think you probably want to open the file once and iterate over it,
but you'll need to figure out what you're trying to do before you can
figure out how to do it in Python :)

Also, be up-front about homework assignments. Honesty won't hurt you
(since we can all tell anyway), and it means we know you're trying to
learn, not to cheat. And yes, there are a discouraging number of
people who do try to cheat, so setting yourself apart from them is
well worth it. :)

Chris Angelico



More information about the Python-list mailing list