Pyton code error

I am new to pyton i am getting an error on pyton code.


   level = elem[prod_pos].count(':')
IndexError: list index out of range

Hi @keerthi2021, I don’t know all the details of this issue, but it seems like you are giving an index to the list, and that index is higher than expected.

Probably, you expected the list to have indexes like this:

["a", "b", "c"]
  1    2    3

However, that’s not the case. Python indexes are more like this:

["a", "b", "c"]
  0    1    2

(Indexes start with 0, not 1). Taking the example above:

>>>foo = ["a", "b", "c"]
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

Maybe that’s your mistake. To fix it, replace the failing line with this one:

   level = elem[prod_pos-1].count(':')

Hope it worked for you :slight_smile:

1 Like

I am not getting any issues with other file. can you let me know how i can print the file name and the linenumber where it is causing the issue.

            for line in infile:
                file_line += 1
                elem = line.split(in_delim)
                level = elem[prod_pos].count(':')
                if level > 0:

Start with asking yourself, what’s the value of “prod_pos”? If prod_pos
is (let’s say) 5, and elem only has 3 items, then it is out of range.
What do you expect it to do when your index is out of range?

You are asking Python to give you the 5th item, but there are only 3
items. What should it do instead?

there was a empty line in the file which cause the issue. removed the empty and the issue was fixed.

Well, that worked for you. However, you may have “empty lines” in the future. You may want to add a conditional to avoid the indexing on empty lines. You don’t have to remove them :slightly_smiling_face:.

thanks @DiddiLeija . can u let me know how to add a conditional to avoid the indexing on the empty lines.

You can use an if statement like this, before manipulating the line:

for line in infile:
    file_line += 1
    if len(line.strip()) < prod_pos - 1:
        # If the length is lower than "prod_pos",
        # then we may not have to index into it.
        # Let's just skip this line
    # whatever you want here...

Actually, it will be useful to avoid lines with a length less than prod_pos - 1 (to ensure that the indexing is possible). Not sure what prod_pos is, so I can’t say a lot about what’s the best practice here.