Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (55.6k points)

Can anyone explain how to take 2d array input in Python?

2 Answers

0 votes
by (119k points)

There are multiple ways to take 2d array input in Python. Here I have mentioned the basic to take 2d array input:

n_rows= int(input("Number of rows:"))

n_columns = int(input("Number of columns:"))

#Define the matrix

matrix = [ ]

print("Enter the entries row-wise:")

#for user input

for i in range(n_rows):          # A for loop for row entries

    a =[ ]

    for j in range(n_cols):      # A for loop for column entries

         a.append(int(input()))

    matrix.append(a)

  

#To print the matrix

for i in range(n_rows):

    for j in range(n_cols):

        print(matrix[i][j], end = " ")

    print( )

Output:

Enter the number of rows:2

Enter the number of columns:3

Enter the entries rowwise:

3

4

5

6

7

8

3 4 5

6 7 8

If you are interested to learn Python from Industry experts, you can sign up this Python Certification by Intellipaat.

You can watch this video on Python tutorial in Hindi by Intellipaat to learn the fundamentals of Python:

How to take 2d array input in Python?
Intellipaat-community
by
The code is not working properly. Change the second line to:
n_cols = int(input("Number of columns:"))
0 votes
by (1.9k points)

If you want to read 2D arrays in Python, this is the easiest way to do it: 

# Input the dimensions 

rows = int(input("Enter number of rows: ")) 

array_2d = [] 

# Accept each row 

for _ in range(rows): 

    row = list(map(int, input("Enter elements of the row, separated by spaces:        ").split())) 

    array_2d.append(row) 

# Print the 2D array 

print("The 2D array is:") 

for row in array_2d: 

print(row) 

Input Rows: Number of rows you need

Input Elements: Each row elements separated by space. 

Store and Print: The elements will be stored in a list that is printed as 2D array. It is pretty straightforward and should help you just fine. Feel free to hear from you again if you have more questions!

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...