1

I have to read an n*n matrix where n and as well the elements of the matrix should be obtained from the user in the console. I understand that Python sees a 2d array to be list in a list. I have read values for a matrix in C and C++. But it seems different in Python. I went through some examples and in all examples I was able to see only compile time input. How do we give user defined output from user?

1

2 Answers 2

3

As you already stated, you will have to use a list of lists.

main_list = []
for i in range(n):
  temp_list = []
  for j in range(n):
    temp_list.append(raw_input("Element {0}:{1}: ".format(i,j)))
  main_list.append(temp_list)
Sign up to request clarification or add additional context in comments.

5 Comments

Can you also tell me how to traverse through the elements. Like how to locate main_list[i][j], i.e row1 element2 or something like that.
exactly the way you stated. After running this, print main_list in the end. Now this would look similar to C/C++ 2d array. Use python syntax and C/C++ logic that you know to traverse this array/list.
Thank you. But list within lists is lot more confusing as we increase the dimensions.
True but when you are comparing it with a C/C++ array, only the name has changed, you have the same thing everywhere. So your access to an element is like main_list[1][2] at all the places.
Am getting familiar now. Thank you for the help.
1

Generate a list for each row and append them to the main list.

matrix=[]    
for i in xrange(n):
    lst=raw_input().split()
    matrix.append(lst)

1 Comment

But how can you be sure that the number of columns will be same. What if the array is to be of size 3*2

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.