Create NumPy Array from List
Problem Statement
Create a NumPy array from a Python list and return its basic properties.
Background
NumPy arrays are the foundation of numerical computing in Python. Unlike Python lists, NumPy arrays are:
- Homogeneous (all elements same type)
- More memory efficient
- Support vectorized operations
Your Task
Write a function create_array(python_list) that:
- Converts the input list to a NumPy array
- Returns a dictionary with:
- "array": The array as a list
- "shape": The shape as a list
- "dtype": The data type as a string
- "ndim": Number of dimensions
Output Format
Return a dictionary with exactly these four keys.
Example:
[1, 2, 3, 4, 5]
{'array': [1, 2, 3, 4, 5], 'shape': [5], 'dtype': 'int64', 'ndim': 1}np.array converts list to ndarray with inferred dtype
Constraints:
- Use numpy.array() to create the array
- Input can be 1D or 2D list
- Return dtype as string
1. Background Knowledge
NumPy is the foundational Python library for numerical computing, providing efficient ndarray (N-dimensional array) objects that enable array programming—a paradigm for vectorized operations on multidimensional data. Unlike Python lists (heterogeneous, dynamic sizing), NumPy arrays are:
- Homogeneous: All elements share the same dtype (data type, e.g., int64, float64).
- Fixed-size: Shape is immutable after creation.
- Memory-efficient: Contiguous storage with O(1) random access.
Key properties for this problem:
- np.array(): Converts lists/iterables to ndarray, inferring dtype and shape.
- arr.shape: Tuple of dimensions (e.g., (5,) for 1D, (3,4) for 2D).
- arr.ndim: Integer count of dimensions.
- arr.dtype: Data type object (convert to string via str(arr.dtype)).
Prerequisites: Import numpy as np; understand list-to-array conversion handles nested lists for multi-D arrays.
2. Algorithm Approach
Direct conversion using np.array() followed by property extraction—no complex algorithms needed, as NumPy handles inference in O(n) time where n is total elements.
Core technique: Array creation + attribute access.
import numpy as np
arr = np.array(python_list) # Infers shape, dtype automatically
Supports 1D ([1,2,3] → shape=(3,)), 2D ([[1,2],[3,4]] → shape=(2,2)), etc.
3. Step-by-Step Strategy
- Import NumPy: import numpy as np.
- Create array: arr = np.array(python_list) (handles 1D/2D per constraints).
- Extract properties:
- "array": arr.tolist() (ndarray → list).
- "shape": list(arr.shape) (tuple → list).
- "dtype": str(arr.dtype) (e.g., 'int64').
- "ndim": arr.ndim (integer).
- Return dictionary: return {"array":..., "shape":..., "dtype":..., "ndim":...}.
Complete solution:
import numpy as np
def create_array(python_list):
arr = np.array(python_list)
return {
"array": arr.tolist(),
"shape": list(arr.shape),
"dtype": str(arr.dtype),
"ndim": arr.ndim
}
Test: create_array([[1,2],[3,4]]) → {'array': [[1,2],[3,4]], 'shape': [2,2], 'dtype': 'int64', 'ndim': 2}.
4. Common Pitfalls
- Missing tolist(): Returning arr directly fails (ndarray ≠list).
- Shape as tuple: Must convert arr.shape to list per spec.
- dtype string: Use str(arr.dtype), not arr.dtype.name (handles all cases).
- 2D input: Nested lists auto-convert; uneven nesting raises ValueError.
- Empty lists: [] → shape=(), ndim=0; np.array([]).tolist() → [].
- No import numpy: Runtime error.
- Mutable input: np.array() copies data safely.
5. Time & Space Complexity
- Time: O(n) for conversion (scan n elements to infer dtype/shape) + O(n) for tolist(). Property access is O(1).
- Space: O(n) for new array + O(n) output lists + O(d) metadata (d= dimensions, typically small). Total: O(n).
Scalability: Linear in input size; NumPy's contiguous storage ensures cache efficiency for large n.