How To Make A 2D Array In Python

In this tutorial, we will learn how to create a 2D array in Python using lists and the numpy library. A 2D array (also known as a matrix) is a tabular way of storing data in rows and columns. It is versatile and widely used in many programming languages, including Python. Let’s get started.

Step 1: Create a 2D Array Using Python Lists

Python lists are a simple, flexible, and built-in data structure that can easily be nested to create a 2D array. Here is how to create a 2D array using nested Python lists:

Step 2: Create a 2D Array Using Numpy

Numpy is a powerful library for numerical computing in Python, and it provides a convenient way to create and work with 2D arrays, among other things. First, you need to install numpy if you haven’t already:

Once you have numpy installed, import the library and create a 2D array:

Full Code

Output

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Conclusion

In this tutorial, we learned how to create a 2D array in Python using nested lists and the numpy library.

Python lists provide a simpler way to create 2D arrays, but using numpy comes with the advantage of having a lot of useful built-in functions and optimized performance for numerical operations.

Depending on your needs and the problem you are trying to solve, you can choose the best method to create a 2D array in Python.