You recover the dimensions of a NumPy matrix with array.shape, which returns a tuple like (3, 4) for 3 rows and 4 columns; in older matrix-specific code you can also use matrix.shape. The key condition is that dimensions describe length along each axis, not the total count of values—array.ndim gives the number of axes, and array.size gives the total element count. If you need both axes as separate variables, unpack the tuple: rows, cols = array.shape. That three-attribute check (shape, ndim, size) answers nearly every "what are the dimensions?" question before you write a single loop.
What "dimensions" means for a NumPy array, and why the word is ambiguous
People use "dimensions" for three different measurements, and mixing them up causes real bugs. The first is shape: the length along each axis. A 2D array of 5 rows and 3 columns has shape (5, 3). The second is ndim: how many axes exist. That same array has ndim == 2. The third is size: the product of the shape, so 15 elements. A common mistake is saying a matrix "has 15 dimensions" when it has 15 elements across two dimensions.
The shape is what you almost always want when you ask about matrix dimensions, because it determines whether operations are legal. Matrix multiplication checks inner dimensions; reshaping checks that the total element count is preserved; plotting libraries read rows and columns to orient data. ndim matters for code that branches on whether input is 1D, 2D, or higher. size matters for memory and alignment questions.
NumPy arrays have no fixed "rows and columns" concept beyond what shape implies. A 1D array of length 4 has shape (4,)—one axis, not four rows and one column. This differs from MATLAB, where everything is at least 2D, and it's a frequent source of confusion when porting code. Treating a 1D array as a column vector requires an explicit reshape to (4, 1).
The direct method: read .shape and unpack it
The shortest recovery is an attribute access. Given an array a:
1: Confirm the object is actually a NumPy array: type(a) should show numpy.ndarray or a subclass. A Python list has no .shape. 2: Read a.shape. Expect a tuple, one entry per axis, in axis order. 3: If you need individual axis lengths, unpack: rows, cols = a.shape. This raises ValueError if the array isn't 2D, which is itself useful information.
A quick check confirms success: compare a.shape against the input you constructed. If you built the array from a list of three lists each holding four numbers, the shape must be (3, 4). If it prints (12,), the nesting collapsed—often because you passed a flat list—and you should inspect the construction step rather than the shape attribute.
Unpacking is the cleanest way to recover row and column counts for genuine 2D data. Avoid indexing like a.shape and a.shape scattered through code; name the values once. For arrays that may be 1D or 2D, guard the unpack or inspect ndim first.
When the object is a numpy.matrix
The numpy.matrix type—distinct from numpy.ndarray—always has exactly two dimensions, and .shape returns a 2-tuple such as (3, 4). Its dimensions are recovered identically. However, numpy.matrix is legacy: the NumPy documentation has long recommended ndarray instead, because matrix forces 2D behavior and changes operator semantics (for example, * means matrix multiplication rather than elementwise multiplication). If you inherit matrix code, .shape still works; if you're writing new code, prefer ndarray and @ for matrix products. The recovery step is the same either way, which is convenient during migration.
Recovering dimensions for 1D and n-dimensional arrays
Higher-dimensional arrays extend the same idea. A 3D array might have shape (2, 3, 4): two blocks, three rows each, four columns each. Unpacking into three names works the same way. ndim reports 3, and size reports 24.
For 1D arrays, shape is a 1-tuple: (7,). The trailing comma is syntax, not a second dimension. Writing n, = a.shape unpacks a single-axis shape correctly; writing n = a.shape is equivalent and often clearer. A bare rows, cols = a.shape on a 1D array fails, which is the guardrail you want—it prevents silently treating a vector as a matrix.
To distinguish these cases deliberately, branch on a.ndim. Code that must accept either a vector or a matrix commonly does something like: if ndim == 1, treat the array as a single row or column according to the caller's convention; if ndim == 2, unpack rows and columns; otherwise raise. That explicit handling beats guessing from size, since a 2×6 array and a 3×4 array both have size 12.
| Attribute | Returns | Example for shape (3, 4) | Typical use |
|---|---|---|---|
| a.shape | Tuple of axis lengths | (3, 4) | Row/column counts, compatibility checks |
| a.ndim | Integer axis count | 2 | Branching on array rank |
| a.size | Integer total elements | 12 | Memory, alignment, flattening checks |
| len(a) | Length of first axis | 3 | Iteration, row counting only |
Note that len(a) reports only the first axis, so for a 3D array it tells you nothing about the other axes. Use shape when all axes matter.
Common failure cases and how to tell them apart
AttributeError: 'list' object has no attribute 'shape'. The input isn't an array yet. Convert with numpy.asarray or numpy.array, then read shape. Don't assume conversion preserves nesting—ragged lists produce object arrays (or errors in newer NumPy), and their shape won't reflect your intended matrix.
Shape looks transposed. A (4, 3) result when you expected (3, 4) means your data was built column-wise, or a transpose happened upstream. This is not a recovery failure; the shape faithfully reports the data. Trace where the array was constructed or transposed.
Unexpected (12,) for nested input. The nesting was flattened. This happens when you build an array from a flat list, when you slice in a way that drops an axis, or when a library returns a flattened result. Check the construction path before adjusting downstream code.
Shape changed after indexing or slicing. Slicing with an integer drops an axis—a on a (3, 4) array yields shape (4,)—while slicing with a range keeps it: a[0:1] yields (1, 4). If dimensions seem to vanish, suspect integer indexing.
matrix vs ndarray surprises. Mixing the two types can produce results whose shape you didn't predict, especially with broadcasting. Standardizing on ndarray removes a class of shape questions entirely.
For all of these, the reversible first step is to print type(a), a.shape, and a.ndim immediately after the array is created, then again after each transformation. That pinpoints the operation that changed the dimensions rather than guessing at the end of a pipeline.
Why recovering shape matters beyond printing it
Dimension recovery is usually a precondition for something else. Matrix multiplication requires the left operand's second dimension to equal the right operand's first; NumPy raises an error when they don't, and the message references shapes. Reshaping requires that the new shape's product equals size; passing -1 in one position lets NumPy infer it, but only if the remaining dimensions divide the total evenly. Broadcasting aligns trailing dimensions, so a (3, 1) array combines with a (1, 4) array to produce (3, 4).
A worked example clarifies the arithmetic. Suppose A has shape (5, 3) and B has shape (3, 2). Their product has shape (5, 2), and the total is 10 elements before any other operations. If instead B is (2, 3), the product is undefined; the inner dimensions 3 and 2 disagree. Recovering both shapes first tells you which case you're in without waiting for an exception. The same logic applies to concatenation, which checks all dimensions except the concatenation axis, and to stacking, which requires identical shapes.
Beyond legality, shape drives memory layout and performance. A (1000, 1000) float array holds a million values; at 8 bytes each, that's about 8 MB. Doubling both axes quadruples the count to four million values and roughly 32 MB—a concrete reason to recover dimensions before allocating. These are illustrative figures based on standard float64 size, not measured benchmarks, but the scaling relationship holds.
Convert, view, or query: choosing the right recovery tool
Sometimes you don't just want to read dimensions; you want them as plain Python integers for serialization or logging. a.shape returns a tuple of Python ints, which serializes cleanly to JSON after conversion with tuple(a.shape) (already a tuple) or list(a.shape) for JSON arrays. No special conversion of element types is needed for standard arrays.
Sometimes you want a size along a specific axis. a.shape[axis] is correct and explicit. numpy.size(a, axis=0) returns the same number for that axis and fails informatively for out-of-range axes. Prefer one convention in a codebase; mixing shape and size(a, 0) is harmless but inconsistently readable.
If you're recovering dimensions from a matrix-like object that isn't a NumPy array—pandas DataFrames expose .shape too, as (rows, columns)—the attribute name is often shared, but the semantics of what a "row" means differ. For sparse matrices from SciPy, .shape still reports the logical dimensions, while .nnz reports stored nonzeros. Don't confuse logical dimensions with stored values.
A stop condition worth naming: if shape recovery is failing because of custom subclasses overriding attributes, or because array-like wrappers (deep learning tensors, GPU arrays) are involved, check that library's own dimension API rather than forcing NumPy semantics. When in doubt, convert to a plain ndarray with numpy.asarray in a scratch context to see the underlying dimensions, then consult the wrapper's documentation for the production path.
Putting it together: a reliable sequence
The practical checklist for recovering matrix dimensions: verify the object type, read shape, check ndim when rank is uncertain, unpack only into as many names as there are axes, and compare against the construction input. Use size for totals, len only for the first axis, and standardize on ndarray over legacy matrix. Most dimension bugs are construction or indexing bugs wearing a disguise, and the shape attribute is the cheapest way to see through it.