How To Take A 2D Array Input In Python

In this tutorial, we will learn how to take a 2D array input in Python. A 2D array is a list of lists and can be thought of as a matrix consisting of rows and columns.

Step 1: Initialize an Empty Array

First, let’s initialize an empty list that will hold our 2D array input.

Step 2: Take the Input for the 2D Array

Now, we’ll take the user’s input for the dimensions of the array (number of rows and columns).

Make sure to convert the user input to integers using int().

Step 3: Populate the 2D Array

We can now use a nested loop to take the input for each element of the array. The outer loop iterates through the rows and the inner loop iterates through the columns.

Step 4: Display the 2D Array

Now, we can display the 2D array using a nested loop to print out each element.

Full Code

Output

Enter the number of rows of the 2D array: 3
Enter the number of columns of the 2D array: 3
Enter the element in 1 row and 1 column: 1
Enter the element in 1 row and 2 column: 2
Enter the element in 1 row and 3 column: 3
Enter the element in 2 row and 1 column: 4
Enter the element in 2 row and 2 column: 5
Enter the element in 2 row and 3 column: 6
Enter the element in 3 row and 1 column: 7
Enter the element in 3 row and 2 column: 8
Enter the element in 3 row and 3 column: 9
The 2D array is:
1 2 3 
4 5 6 
7 8 9 

Conclusion

In this tutorial, we have learned how to take a 2D array input in Python. We used a nested loop to populate and display the 2D array based on user input. This can be helpful when working with arrays, such as in matrix operations.