Skip to content

numpy/growth-in-loop

Pack Severity Fix Versions
NumPy warning none, edit by hand All versions

Growing an array with np.append or np.concatenate in a loop copies every earlier value on each pass. Collect the pieces in a list and call np.concatenate once after the loop.

out = np.array([])
for part in parts:
out = np.append(out, part)
out = np.concatenate(parts)

The rule reports out = np.append(out, x), out = np.concatenate((out, x)) and the same with vstack, hstack, column_stack, dstack and stack inside a loop that doesn't reset out or read it elsewhere. Each call copies every earlier value.

The rule leaves assignments such as rows = np.vstack(parts_of_this_row) alone because they build a fresh array. It also leaves an append next to an assignment that updates the same array, such as a preceding np.delete, alone.

xpd has no automatic fix, so make the change by hand.

$OUT grows by one $NP.$F per pass, and each call copies every earlier value. Collect the pieces in a list and call np.concatenate once after the loop, which ran 130 to 170 times faster for 1,000 passes over 1,000,000 values.

See all rules in the NumPy pack.