How To Print 2D Array In Python

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:

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:

For example, to access the element in the first row and second column, we can use:

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.

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:

This will give us the same output as before.

The Full Code

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.