How to Check Shape of Data in Python Easily
To check the shape of data in Python, use
.shape for NumPy arrays and pandas DataFrames, which returns the dimensions as a tuple. For lists, use len() for length or nested loops to find dimensions.Syntax
Here are common ways to check the shape of data in Python:
array.shape: Returns a tuple with the size of each dimension for NumPy arrays or pandas DataFrames.len(list): Returns the length of a list (number of elements).
python
import numpy as np import pandas as pd # NumPy array shape array = np.array([[1, 2, 3], [4, 5, 6]]) print(array.shape) # (2, 3) # pandas DataFrame shape df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) print(df.shape) # (2, 2) # List length lst = [1, 2, 3, 4] print(len(lst)) # 4
Output
(2, 3)
(2, 2)
4
Example
This example shows how to check the shape of a NumPy array, a pandas DataFrame, and a nested list.
python
import numpy as np import pandas as pd # Create a 3x4 NumPy array np_array = np.arange(12).reshape(3, 4) print('NumPy array shape:', np_array.shape) # Create a pandas DataFrame with 3 rows and 2 columns df = pd.DataFrame({'X': [10, 20, 30], 'Y': [40, 50, 60]}) print('DataFrame shape:', df.shape) # Nested list (3 rows, 4 columns) nested_list = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print('List length:', len(nested_list)) print('Length of first inner list:', len(nested_list[0]))
Output
NumPy array shape: (3, 4)
DataFrame shape: (3, 2)
List length: 3
Length of first inner list: 4
Common Pitfalls
Some common mistakes when checking data shape include:
- Using
len()on nested lists only gives the outer list size, not full dimensions. - Trying to use
.shapeon plain Python lists causes errors because lists don't have this attribute. - Confusing rows and columns order in the shape tuple.
python
lst = [[1, 2], [3, 4]] # Wrong: This will cause an error # print(lst.shape) # AttributeError: 'list' object has no attribute 'shape' # Right: Use len() for outer and inner lists print(len(lst)) # 2 (number of rows) print(len(lst[0])) # 2 (number of columns)
Output
2
2
Quick Reference
Summary of how to check shape or size of data in Python:
| Data Type | How to Check Shape/Size | Returns |
|---|---|---|
| NumPy array | array.shape | Tuple of dimensions (rows, columns, ...) |
| pandas DataFrame | df.shape | Tuple of (rows, columns) |
| Python list | len(list) | Length of outer list |
| Nested list | len(list) and len(list[0]) | Outer and inner list lengths |
Key Takeaways
Use
.shape to get dimensions of NumPy arrays and pandas DataFrames.For plain Python lists, use
len() to find length; nested lists need checking inner lists separately.Trying
.shape on lists causes errors because lists don't have this attribute.The shape tuple shows (rows, columns) order for 2D data structures.
Always verify data type before checking shape to avoid mistakes.