1

I've been trying to create a matrix, with single line input, like, if I enter "1 2 3" it should go like l[0][0]=[1,2,3]

for i in range(num):
  for j in range(num):
    l[i][j] = input().spilt()

It gives index out of range error, which I understand why it gives, since we are fixing j index at point of loop, which means we locking it to one entry and giving multiple input, which is contradicting, for removing the limiter, I modified it like this:

for i in range(num):
  l[i] = input().spilt()

I know this totally wrong, It is no where near to 2D matrix, but I'm totally screwed thinking over this.

Hououin Kyouma
  • 163
  • 1
  • 2
  • 8
  • What is your desired output? – user3483203 Sep 09 '18 at 07:48
  • `index out of range` is raised by the `l[i][j]` expression for some value of `i` or `j`. Evidently `l` is a list or list of lists, and isn't as big as the `num` range. WIthout knowing how you created `l` we really can't help you. You can certainly put a list `['1','2','3']` in another list. – hpaulj Sep 09 '18 at 15:48
  • At some level you are confusing Python lists with numpy arrays (and possibly `np.matrix` array subclass). – hpaulj Sep 09 '18 at 15:51
  • 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 10:08

1 Answers1

1

Based on your description, it looks like you would want to do the following:

l = []
for _ in range(num):
    l.append(input().split())

Please note that split() is returning strings (that were parts of the input) and not integer numbers. If you want to have a list of lists of numbers (i.e., float or int), then you will want to convert strings to numbers of appropriate type:

l = []
for _ in range(num):
    l.append(list(map(float, input().split()))) # float <-> int (if needed)

or, if you insist on one-liners:

l = [list(map(float, input().split())) for _ in range(num)]

Also note that Python does not have the notion of 2D arrays. That is a concept in the numpy package. You also tagged your question with numpy. So, if your purpose is to input a square 2D numpy array you could do the following:

import numpy as np
l = np.array([input('Enter line: ').split() for _ in range(num)], dtype=np.float)

Example:

In [18]: np.array([input('Enter line: ').split() for _ in range(num)], dtype=np.float)
Enter line: 1 2 3
Enter line: 4 5 6
Enter line: 7 8 9
Out[18]: 
array([[1., 2., 3.],
       [4., 5., 6.],
       [7., 8., 9.]])
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45