numpy/growth-in-loop
| Rule | growth-in-loop |
|---|---|
| Pack | NumPy |
| Severity | warning |
| Fix | none, edit by hand |
| Library versions | every version |
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)What the rule reports
Section titled “What the rule reports”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.
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so make the change by hand.
Message
Section titled “Message”xpd prints this message with the issue. A name that starts with $ stands for code from your file.
$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.Browse the other rules of the NumPy pack.