0

I want that user give input like this

[[3,4,5],[7,2,1]]

and it will create a 2d array automatically and store in a. so when print(a) will given it returns

a=[[3,4,5],[7,2,1]]

where type(a[0][0]) i mean all elements inside a will be int. How can I do it?

The Movie
  • 19
  • 3
  • 1
    Welcome to SO! You should share what you have tried or how you can't find the answer elsewhere. Have you looked at [other posts](https://stackoverflow.com/a/28165771/13386979)? – Tom Feb 03 '21 at 04:51
  • 1
    Does this answer your question? [taking n\*n matrix input by user in python](https://stackoverflow.com/questions/32466311/taking-nn-matrix-input-by-user-in-python) – Gino Mempin Feb 03 '21 at 06:02

2 Answers2

1

Input:

2 // no.of rows
3 // no.of columns
1 2 3 
4 5 6

Output:

[[1,2,3],[4,5,6]]

Solution:

r = int(input())

c = int(input()) 

a = [list(map(int,input().split())) for _ in range(r)] 

print(a)

The variable c isn't used in the code, so you can simply get it as a string and also ignore the assignment using input()

Line 3 involves List Comprehension (documentation).

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
0
n = int(input())
m = int(input())
input_list = []
for i in range(n):
    list1 = []
    for j in range(m):
        z = int(input())
        list1.append(z)
    input_list.append(list1)
print(input_list)

Okay so we take the size of the 2-d array from the user in n and m resp. We create an empty list named as input_list. Now we run a loop for n times so this will be the number of rows in the 2-d array. for every row we create a list named as list1. Run a loop to take inputs from the user on the elements in the row. Then we append the newly created row (list1) in the input_list.This action is performed for all the rows. And when the execution finishes we get the input_list as a 2-d array.