Skip to content Skip to sidebar Skip to footer

Multidimensional Array By User Input In Python

I used Jupyter notebook, I am new to Python, I try to fetch value from user in multidimensional array how I do that? I write a little code, after put first value I get error that I

Solution 1:

I took @Austin great answer and made some little changes:

import numpy as np

n_rows = int(input("Enter number of rows: "))
n_cols = int(input("Enter number of columns: "))

arr = [[int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1))) for c inrange(n_cols)] for r inrange(n_rows)]

print(np.array(arr))

The output is:

Enter number ofrows: 2
Enter number of columns: 3
Enter valuefor1.rowand1.column: 1
Enter valuefor1.rowand2.column: 2
Enter valuefor1.rowand3.column: 3
Enter valuefor2.rowand1.column: 4
Enter valuefor2.rowand2.column: 5
Enter valuefor2.rowand3.column: 6
[[123]
 [456]]

You got an exception, because you initialized an empty array and used invalid indices. With this answer you generate the array after you have entered the users input.


Here is the long version of the one-liner (arr = [[...) which gives you the same result:

outer_arr = []
for r in range(n_rows):
    inner_arr = []
    for c in range(n_cols):
        num = int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1)))
        inner_arr.append(num)
    outer_arr.append(inner_arr)

print(np.array(outer_arr))

Solution 2:

You can use a list-comprehension here as the final result is a list of lists:

lengthrow = int(input("enter array row length: "))
lengthcol = int(input("enter array col length: "))

arr = [[int(input("enter value: ")) for _ inrange(lengthcol)] for _ inrange(lengthrow)]

print(arr)

Problem with your code:

arr = array([[],[]])
print(arr.shape)
# (2, 0)

That means you have a size 0 column in array, so when you do arr[0][0], for example, it throws error.

Solution 3:

The problem is the shape of the initial array:

In [1]: arr = np.array([[], []])
In [2]: arr
Out[2]: array([], shape=(2, 0), dtype=float64)
In [3]: arr[0]
Out[3]: array([], dtype=float64)
In [4]: arr[0][0]
... 
IndexError: index 0isoutof bounds for axis 0with size 0

Think of this array as 2 rows, 0 columns. You can't reference a non-existent column. And, in contrast to some other languages, you can't grow an array simply by referencing a new index. Once created the size is fixed.

While others have shown nice list comprehension approaches, I'll show how to use your approach correctly:

In [8]: lengthrow, lengthcol = 2,3    # or user input
In [9]: arr = np.zeros((lengthrow, lengthcol), dtype=int)  # large enough array
In [10]: arr
Out[10]: 
array([[0, 0, 0],
       [0, 0, 0]])
In [11]: for i in range(2):
    ...:     for j in range(3):
    ...:         arr[i,j] = int(input(f'{i},{j}:'))
    ...:         
0,0:00,1:10,2:21,0:31,1:41,2:5
In [12]: arr
Out[12]: 
array([[0, 1, 2],
       [3, 4, 5]])

Post a Comment for "Multidimensional Array By User Input In Python"