Sean
Sean

Reputation: 1313

List out of index error Python

I seem to be getting a strange list index out of range error:

Traceback (most recent call last):
File "./test.py", line 7, in <module>
print  column[2]
IndexError: list index out of range

For this simple line of code,

DIR = 'path/to/test.vcf'

for line in open(DIR):
        column = line.split()
        print  column[2]

Where column outputs:

['chr1', '19964150', '.', 'AAAAGAAAAAGAAAAAGAA', '.', '0', '.','END=19964169;MOTIF=AAAAAG;REF=3.16667;RL=19;RPA=.;RU=AAAAGA;VT=STR', 'GT:ALLREADS:AML:DP:GB:PL:Q:STITCH', '0/0:0|6:1/1:6:0/0:0:1:1']

column[0] outputs:

chr1

But any other integer index and it gives me an error Why would I be receiving this error if column is a list with 10[9 by list logic] split strings?

Upvotes: 0

Views: 103

Answers (1)

falsetru
falsetru

Reputation: 369054

There should be line(s) that does not match your expectation. (line with less columns / blank line).

Guard the line that access the third column to avoid the exception.

DIR = 'path/to/test.vcf'

for line in open(DIR):
    column = line.split()
    if len(column) > 2:
        print column[2]

Upvotes: 3

Related Questions