numpy
python
data-structures
lists
arrays

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

python
1import numpy as np
2
3# Equal-length sublists → 2D array
4data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
5arr = np.array(data)
6
7print(arr)
8# [[1 2 3]
9#  [4 5 6]
10#  [7 8 9]]
11
12print(arr.shape)  # (3, 3)
13print(arr.dtype)  # int64

NumPy infers the shape and dtype from the data.

Setting the dtype

python
1# Force float type
2arr = np.array([[1, 2], [3, 4]], dtype=np.float32)
3print(arr.dtype)  # float32
4
5# Force specific integer type
6arr = np.array([[1, 2], [3, 4]], dtype=np.int8)
7print(arr.dtype)  # int8
8
9# Mixed int and float → all promoted to float
10arr = np.array([[1, 2.5], [3, 4]])
11print(arr.dtype)  # float64

Ragged lists of different lengths

python
1ragged = [[1, 2, 3], [4, 5], [6]]
2
3# NumPy 1.24+ raises a warning/error by default
4arr = np.array(ragged, dtype=object)
5print(arr)
6# [list([1, 2, 3]) list([4, 5]) list([6])]
7print(arr.shape)  # (3,) — 1D array of Python objects
8print(arr.dtype)  # object

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:

python
1from itertools import zip_longest
2
3ragged = [[1, 2, 3], [4, 5], [6]]
4
5# Pad with zeros
6padded = list(zip_longest(*ragged, fillvalue=0))
7arr = np.array(padded).T
8print(arr)
9# [[1 2 3]
10#  [4 5 0]
11#  [6 0 0]]
12
13# Or use a helper function
14def pad_to_array(lists, fill=0):
15    max_len = max(len(row) for row in lists)
16    return np.array([row + [fill] * (max_len - len(row)) for row in lists])
17
18arr = pad_to_array(ragged)
19print(arr.shape)  # (3, 3)

3D and higher dimensions

Deeper nesting gives more dimensions:

python
1# 3D: list of matrices
2data_3d = [
3    [[1, 2], [3, 4]],
4    [[5, 6], [7, 8]]
5]
6arr = np.array(data_3d)
7print(arr.shape)  # (2, 2, 2)
8
9# Access elements
10print(arr[0, 1, 0])  # 3 (first matrix, second row, first column)

Faster conversion: np.fromiter, preallocation, np.vstack

python
1import time
2
3# List of lists — standard conversion
4data = [[i, i+1, i+2] for i in range(100000)]
5
6start = time.time()
7arr = np.array(data)
8print(f"np.array: {time.time() - start:.4f}s")
9
10# For flat data, np.fromiter is faster
11flat = [x for row in data for x in row]
12start = time.time()
13arr = np.fromiter(flat, dtype=int, count=len(flat)).reshape(-1, 3)
14print(f"np.fromiter: {time.time() - start:.4f}s")

For very large datasets, consider np.vstack, np.stack, or preallocating the array:

python
1# Pre-allocate and fill (fastest for known shapes)
2rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3arr = np.empty((len(rows), len(rows[0])), dtype=np.float64)
4for i, row in enumerate(rows):
5    arr[i] = row
6
7# np.vstack from a list of 1D arrays
8arrays = [np.array([1, 2, 3]), np.array([4, 5, 6])]
9arr = np.vstack(arrays)
10print(arr.shape)  # (2, 3)

Tuples, arrays and DataFrames

python
1# List of tuples
2data = [(1, 2), (3, 4), (5, 6)]
3arr = np.array(data)  # (3, 2) array
4
5# List of NumPy arrays
6arrays = [np.array([1, 2]), np.array([3, 4])]
7arr = np.stack(arrays)  # (2, 2) array
8
9# Pandas DataFrame to NumPy
10import pandas as pd
11df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
12arr = df.to_numpy()  # (2, 2) array

Mistakes to watch for

  • Ragged lists: older NumPy versions turned np.array([[1,2], [3]]) into a 1D array of list objects (with a VisibleDeprecationWarning from NumPy 1.19 through 1.23). From 1.24 it raises ValueError unless you pass dtype=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 dtype object or <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. Use np.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, or pandas.read_csv().to_numpy().
  • Memory order: order='C' (the default) creates row-major arrays and order='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.


Course
Intermediate
27 lessons
15 hours
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 course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design