2

I want to read a square matrix like this from the console using python:

1 2 3 
2 1 6
5 1 2

I tried using this:

matrix = [[int(input()) for x in range (n)] for y in range(n)]

But here each element can be given line by line and not like a matrix. We can also read it as a single line but how do I read it like above?

Akhila
  • 489
  • 6
  • 18

2 Answers2

1

You can do this with this:

n=3
[list(map(int, input().split(' '))) for y in range(n)]

Input/Output:

1 2 3
2 1 6
5 1 2
Out[50]: [[1, 2, 3], [2, 1, 6], [5, 1, 2]]
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
1

@oppressionslayer's answer works but accepts only a matrix of a fixed size as defined by n. Since the number of rows is to be equal to the number of columns, you can simply get the number of columns from the first input and stop taking input when the user enters the same number of rows:

l = []
while not l or len(l) < len(l[0]):
    l.append(list(map(int, input().split())))

so that given an input of:

1 2 3 
2 1 6
5 1 2

l would become:

[[1, 2, 3], [2, 1, 6], [5, 1, 2]]
blhsing
  • 91,368
  • 6
  • 71
  • 106