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?
2 Answers
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)
5 Comments
sarvai
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.
Barun Sharma
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.sarvai
Thank you. But list within lists is lot more confusing as we increase the dimensions.
Barun Sharma
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.
sarvai
Am getting familiar now. Thank you for the help.
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
Pavan Nath
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