How to Create a 2D Array in NumPy: Simple Guide
To create a 2D array in NumPy, use the
numpy.array() function with a list of lists as input. Each inner list represents a row, forming a matrix-like structure.Syntax
The basic syntax to create a 2D array in NumPy is:
numpy.array(object): Converts the inputobject(usually a list of lists) into a NumPy array.- Each inner list represents a row in the 2D array.
python
import numpy as np array_2d = np.array([[1, 2, 3], [4, 5, 6]])
Example
This example shows how to create a 2D array with two rows and three columns, then print it.
python
import numpy as np array_2d = np.array([[10, 20, 30], [40, 50, 60]]) print(array_2d)
Output
[[10 20 30]
[40 50 60]]
Common Pitfalls
Common mistakes when creating 2D arrays include:
- Using uneven inner lists, which creates an array of lists instead of a 2D numeric array.
- Forgetting to import NumPy before using
np.array(). - Passing a flat list instead of a list of lists, which creates a 1D array.
python
import numpy as np # Wrong: uneven inner lists array_wrong = np.array([[1, 2], [3, 4, 5]]) print(array_wrong) # Right: even inner lists array_right = np.array([[1, 2, 0], [3, 4, 5]]) print(array_right)
Output
[list([1, 2]) list([3, 4, 5])]
[[1 2 0]
[3 4 5]]
Quick Reference
Tips for creating 2D arrays in NumPy:
- Use
np.array()with a list of lists. - Ensure all inner lists have the same length.
- Check the shape with
.shapeattribute. - Use
dtypeparameter to specify data type if needed.
Key Takeaways
Use np.array() with a list of lists to create a 2D array.
All inner lists must have the same length for a proper 2D array.
Check the array shape with the .shape attribute.
Avoid uneven inner lists to prevent creating arrays of lists.
Always import NumPy before creating arrays.