Arrays from Lists
So you want to create arrays from Python lists? That's where it all starts. Think of it like converting your messy notes into a neat spreadsheet.
1D Arrays
The simplest case - just pass a flat list to np.array().
import numpy as np
my_list = [10, 20, 30, 40, 50]
arr_1d = np.array(my_list)
print(f"1D Array: {arr_1d}")
print(f"Shape: {arr_1d.shape}")
print(f"Dimensions: {arr_1d.ndim}")
Notice the shape is (5,) - that's a tuple with one element. The comma is important because it tells Python this is a tuple, not just parentheses around a number.
2D Arrays (Matrices)
Use nested lists to create 2D arrays. Each inner list becomes a row.
import numpy as np
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix = np.array(nested_list)
print(f"2D Array:\n{matrix}")
print(f"Shape: {matrix.shape}")
print(f"Dimensions: {matrix.ndim}")
Here is the thing - all rows must have the same number of elements. If they don't, NumPy will create an array of arrays instead of a proper 2D array.
3D Arrays
For 3D arrays, you need three levels of nesting. Think of it like a stack of matrices.
import numpy as np
nested_3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
cube = np.array(nested_3d)
print(f"3D Array:\n{cube}")
print(f"Shape: {cube.shape}")
print(f"Dimensions: {cube.ndim}")
One thing that confused me at first was the shape interpretation. For 3D, shape (2, 2, 2) means 2 blocks, 2 rows per block, 2 columns per row.
Try it Yourself →Key Takeaways
- Use nested lists to create multi-dimensional arrays
- All rows in 2D arrays must have the same length
- Shape tuple shows dimensions at each level
- 3D arrays are stacks of 2D matrices