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:
1 2 |
# 2D array using Python lists array_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
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:
1 |
!pip install numpy |
Once you have numpy installed, import the library and create a 2D array:
1 2 3 4 |
import numpy as np # 2D array using numpy array_numpy = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) |
Full Code
1 2 3 4 5 6 7 |
import numpy as np array_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] array_numpy = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(array_list) print(array_numpy) |
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.