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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
sarvai
  • 13
  • 1
  • 5
  • Possible duplicate of [How to input matrix (2D list) in Python?](https://stackoverflow.com/questions/22741030/how-to-input-matrix-2d-list-in-python) – Georgy Jul 12 '19 at 09:23

2 Answers2

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
  • Am getting familiar now. Thank you for the help. – sarvai Sep 13 '15 at 09:48
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