Click here to Skip to main content
15,888,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
iam trying to read and print matrix in python3.6
but it says index out of range error
what could be the problem
def read(l,m,n):
    for i in range(m):
        tl=[]
        for j in range(n):
            tl.append([int(i) for i in input("enter row elements").split()])
            l.append(tl)
        
            
def printm(l,m,n):
    
    for i in range(m):
        for j in range(n):
            print(l[i][j],end=" ")
            
        print()    
m=int(input("enter rows"))
n=int(input("eneter colums"))
l=[]
read(l,m,n)
print()
printm(l,m,n)      


What I have tried:

i tried append method and = operator but it takes only first three values and printing that first three integers in remaining matrix elements
Posted
Updated 28-May-23 23:24pm
Comments
Richard MacCutchan 29-May-23 6:43am    
I just tried your code and it works fine. You need to show us what values you are entering, and what result you see.

1 solution

We don't have your data, so we can't test under the same conditions you do - and that's probably quite important.
Basically, an "index out of range" error means just that: you have a collection with say 3 items, and you are trying to use an index (the bit in square brackets) that isn't 0, 1, or 2 - any other number will give you a range error because Python array indices start from 0 and run to the number of elements minus one. And we have no idea what your data looks like, or where in that code the error occurs!

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. A quick Google for "Python debugger" should give you the info you need to use it.


Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900