Doubt regarding defining function with for loop

def initialise_matrix(user_input1,user_input2):
user_input1 = int(input('Enter the number of rows: '))
user_input2 = int(input('Enter the number of coloumn: '))
a = []
b = []

for i in range(user_input1):    
    for j in range(user_input2):
        b[j] = int(input("enter the elements: "))
        b.append(b[j])
    a.append(b)
return a

x = initialise_matrix(user_input1,user_input2)
x

Q) Why it is showing list assignment out of index range (Index Error)???

Hi Monil

In order to understand this error, you need to know how indexing works with lists.
There would be no index in an empty list. As we append the elements to a list the index keeps incrementing.

In your code, you used b[j] = int(input("enter the elements: ")) Initially b was an empty list so definitely when you access the index then it will give you index out of bounds error.

I hope your question was answered

Thanks

Ohk…thanks Sir…understood!!!

Why are you passing a variable to a function when you are defining it only inside the function ?

Either define it outside a function and the pass it to it for using the values, else if you are defining it inside the function , how are you able to pass it from outside the function .

Recommend you to read this Python Scope of Variables - GeeksforGeeks

Also @kkhatke please go through the mentioned article