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.
1 |
arr = [] |
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).
1 2 |
rows = int(input("Enter the number of rows of the 2D array: ")) columns = int(input("Enter the number of columns of the 2D array: ")) |
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.
1 2 3 4 5 6 7 |
for i in range(rows): row = [] # Initialize an empty list for the current row for j in range(columns): element = int(input(f"Enter the element in {i + 1} row and {j + 1} column: ")) row.append(element) # Append the element to the current row arr.append(row) # Append the current row to the 2D array |
Step 4: Display the 2D Array
Now, we can display the 2D array using a nested loop to print out each element.
1 2 3 4 5 |
print("The 2D array is:") for i in range(rows): for j in range(columns): print(arr[i][j], end=" ") print() # Move to the next line after printing all elements in a row |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
arr = [] rows = int(input("Enter the number of rows of the 2D array: ")) columns = int(input("Enter the number of columns of the 2D array: ")) for i in range(rows): row = [] for j in range(columns): element = int(input(f"Enter the element in {i + 1} row and {j + 1} column: ")) row.append(element) arr.append(row) print("The 2D array is:") for i in range(rows): for j in range(columns): print(arr[i][j], end=" ") print() |
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.