Exception error 'list index out of range.'

Question:

I have a text file (txt_file.txt). Data contain 26 lines as below.

AAA  --> 1st line
BBB
CCC
...
ZZZ -->26th line

I have code for read each line.

with open('txt_file.txt') as file:
    lines = [line.rstrip() for line in file]  
    #print(lines) # or lines[1]
    
subs = [((0, 3), lines[1] +'n'+lines[2]),
        ((4, 7), lines[3] +'n'+lines[4]),
        ((8, 11), lines[5] +'n'+lines[6]),
        ((12, 15), lines[7] +'n'+lines[8]),
       ((16, 19), lines[9] +'n'+lines[10]),
       ((20, 23), lines[11] +'n'+lines[12]),
       ((24, 27), lines[13] +'n'+lines[14]),
       ((28, 31), lines[15] +'n'+lines[16]),
       ((32, 35), lines[17] +'n'+lines[18]),
       ((36, 39), lines[19] +'n'+lines[20]),
       ((40, 43), lines[21] +'n'+lines[22]),
       ((44, 47), lines[23] +'n'+lines[24]),
       ((48, 51), lines[25] +'n'+lines[26]),
       ((52, 55), lines[27] +'n'+lines[28]),
       ((56, 59), lines[29] +'n'+lines[30]),]

error ‘list index out of range’ occur.

But I don’t want to change subs = because when I input (txt_file.txt) next time.
It maybe is contained more or less than 26 lines.
I want to exception ‘list index out of range’ error.

Asked By: Kukkik

||

Answers:

Since your numbers are following a linear rule, you can construct them programmatically instead of hardcoding them:

subs = [((4 * i, 4 * i + 3), lines[l + 1] + 'n' + lines[l + 2])
        for i, l in enumerate(range(0, len(lines) - 2, 2))]
Answered By: deceze
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.