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?
Asked
Active
Viewed 5,379 times
2 Answers
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)

Barun Sharma
- 1,452
- 2
- 15
- 20
-
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. – sarvai Sep 12 '15 at 20:30
-
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. – Barun Sharma Sep 12 '15 at 20:35
-
Thank you. But list within lists is lot more confusing as we increase the dimensions. – sarvai Sep 13 '15 at 09:10
-
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. – Barun Sharma Sep 13 '15 at 09:22
-
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)

DataCruncher
- 850
- 7
- 11
-
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 – Pavan Nath Jul 10 '17 at 13:36