In this tutorial, we will learn how to print a 2D (two-dimensional) array in Python. A 2D array is an array within an array, representing a grid of elements, like a matrix or a table. In Python, we don’t have built-in support for arrays, but we can use lists to create 2D arrays.
Step 1: Create a 2D array
To create a 2D array in Python, we can use a nested list, which is essentially a list containing other lists. We can represent each element of the outer list as a row, and elements within the inner lists as columns.
Here’s an example of a 2D array:
1 2 3 4 5 |
arr_2d = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] |
This creates a 3×3 array with three rows and three columns.
Step 2: Access elements in the 2D array
To access elements in a 2D array, we need two indices. We can use the following notation:
1 |
arr_2d[row][column] |
For example, to access the element in the first row and second column, we can use:
1 |
print(arr_2d[0][1]) # Output: 2 |
Step 3: Print the 2D array using nested loops
To print the entire 2D array, we can use nested loops. We’ll first iterate through the rows (outer list) and then iterate through each column (inner list) for every row.
1 2 3 4 |
for row in arr_2d: for col in row: print(col, end=' ') print() |
This will output:
1 2 3 4 5 6 7 8 9
The end=' '
argument in the print()
function is used to avoid a new line after printing each column element. The print()
function without any argument is used to print a new line after each row has been printed.
Step 4: Using List Comprehensions (Optional)
As an alternative, we can also use list comprehensions to print the 2D array in a more concise and readable way. Here’s how we can do it:
1 |
print('\n'.join([' '.join([str(col) for col in row]) for row in arr_2d])) |
This will give us the same output as before.
The Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
arr_2d = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print("Using nested loops:") for row in arr_2d: for col in row: print(col, end=' ') print() print("\nUsing list comprehensions:") print('\n'.join([' '.join([str(col) for col in row]) for row in arr_2d])) |
Conclusion
In this tutorial, we learned how to create a 2D array in Python using nested lists, access its elements, and print the entire array using nested loops and list comprehensions. Now you can easily work with 2D arrays and display them in a readable format in your Python projects.