0

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

2
  • These are lists in Python, not arrays. Commented Mar 30, 2020 at 15:56
  • 3
    final only has 1 element. There's no final[1] so how can you insert into it? Commented Mar 30, 2020 at 15:57

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.