Convert a list of lists into a NumPy array
Codemia Knowledge Hub ·
Pass the list to np.array(). If every inner list has the same length, you get a regular 2D numeric array. If the lengths differ (a ragged list), NumPy cannot build a 2D numeric array: you must pass dtype=object, which gives a 1D array of Python objects and loses the performance of a contiguous numeric array, or pad the rows to equal length first.
Basic conversion
NumPy infers the shape and dtype from the data.
Setting the dtype
Ragged lists of different lengths
In NumPy 1.24 and later, creating a ragged array without dtype=object raises a ValueError. To get a regular numeric array, pad the shorter rows:
3D and higher dimensions
Deeper nesting gives more dimensions:
Faster conversion: np.fromiter, preallocation, np.vstack
For very large datasets, consider np.vstack, np.stack, or preallocating the array:
Tuples, arrays and DataFrames
Mistakes to watch for
- Ragged lists: older NumPy versions turned
np.array([[1,2], [3]])into a 1D array of list objects (with aVisibleDeprecationWarningfrom NumPy 1.19 through 1.23). From 1.24 it raisesValueErrorunless you passdtype=object. Make inner lists the same length for numeric arrays. - dtype promotion from mixed types: one string (
[[1, 2], [3, "four"]]) makes the whole array dtypeobjector<U21, and numeric operations stop working. Validate input types before converting. - Copies:
np.array(existing_array)copies by default;np.asarray(existing_array)does not. Usenp.asarray()to avoid unnecessary copies. - Memory with large lists: converting a 1-million-row list of lists temporarily doubles memory, because the list and the array both exist. For large data, read straight into NumPy with
np.loadtxt,np.genfromtxt, orpandas.read_csv().to_numpy(). - Memory order:
order='C'(the default) creates row-major arrays andorder='F'column-major. The wrong order can significantly slow operations that iterate along the non-contiguous axis.
Check .shape and .dtype after converting to confirm you got what you expected.
Related reading
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.