sarvai
sarvai

Reputation: 13

How to read user defined input for 2d array

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?

Upvotes: 1

Views: 5404

Answers (2)

DataCruncher
DataCruncher

Reputation: 880

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)

Upvotes: 1

Barun Sharma
Barun Sharma

Reputation: 1468

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)

Upvotes: 3

Related Questions