Two-dimensional (2D) arrays in Python are mainly implemented through the use of lists. A list in Python is a linear data structure that can hold heterogeneous types of items. It can be defined as a collection of items that are changeable or mutable.
To create a 2D array, we can use a list of lists, which is basically a list consisting of other lists as its elements. This tutorial will guide you on how to fill a 2D array in Python.
Step 1: Creating an Empty Matrix
To begin filling a 2D array in Python, you must first create an empty matrix where values can be filled in. Below is a simple example of how to create an empty matrix:
1 |
matrix = [[0 for i in range(5)] for j in range(5)] |
Here, we’ve created a 5×5 matrix filled with zeros. You can replace ‘5’ with the number of rows and columns you want for your matrix.
Step 2: Filling the Matrix
Now that we have our matrix, we can fill it with values. There are a variety of ways to do this in Python, but we will cover two main methods: manually filling in values and using a looping statement.
Manually filling in values:
1 |
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
In this example, we’ve filled the matrix with values from 1 to 9.
Using a looping statement:
1 2 3 4 |
matrix = [[0 for i in range(5)] for j in range(5)] for i in range(5): for j in range(5): matrix[i][j] = i*j |
In this example, we’ve used a nested for loop to fill in the matrix with the product of the row and column indices.
Step 3: Confirming the Content
Finally, let’s verify that our 2D array has been filled. We can do this by simply printing the matrix as follows:
1 |
print(matrix) |
This would give the following output for the manual filling example:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
And for the looping statement example, the output would be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8], [0, 3, 6, 9, 12], [0, 4, 8, 12, 16]]
Complete Code
1 2 3 4 5 6 7 8 9 10 |
# creating matrix matrix = [[0 for i in range(5)] for j in range(5)] # filling the matrix for i in range(5): for j in range(5): matrix[i][j] = i*j # printing the matrix print(matrix) |
Conclusion
By following these simple steps, you can fill a 2-dimensional array in Python. Depending on your requirements, you can manually populate the 2D array or use a looping statement. This flexibility is just one of the many reasons why Python is ideal for handling data structures like 2D arrays.