soheib
soheib

Reputation: 90

IndexError: list index out of range python insert to 2d array(list)

hey guys i have a question about 2d lists in python that's my code :

results = []
with open("p100001.psv") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader: 
        results.append((str(row).split("|")))




final=[[[]]]

k = 0
while k < (len(results)-7):
    for i in range(1+k,7+k):
        h = 0
        for j in range(0,41):
            final[k].insert((41*(h)+j),results[i][j])
        h = h+1    
    k = k+1    

when k=0 and code inserting final[0] everything is ok and code working but when code continue and k=1 i have face this error for final[1] : IndexError: list index out of range

Upvotes: 0

Views: 204

Answers (1)

Nilanka Manoj
Nilanka Manoj

Reputation: 3738

You cannot insert to final[k] without having the element in the list. So, you have to insert an empty list to final list in every iteration.

final=[]
k = 0
while k < (len(results)-7):
    final.append([[]])
    for i in range(1+k,7+k):
        h = 0
        for j in range(0,41):
            final[k].insert((41*(h)+j),results[i][j])
        h = h+1    
    k = k+1

Upvotes: 1

Related Questions