Skip to content

numpy/reduce-last

Pack Severity Fix Versions
NumPy warning unsafe, with xpd check --fix --unsafe-fixes All versions

np.cumsum(x)[-1] builds every running total to read the last one, which was 8 times slower and adds rounding. Call np.sum(x).

total = np.cumsum(amounts)[-1]
total = np.sum(amounts)

The rule reports np.cumsum(x)[-1] and np.cumprod(x)[-1].

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes np.sum(x), np.prod(x).

A floating-point reduction can round differently. On an empty array, indexing the last element raises while a full reduction returns its identity value.

This builds every running total to read the last one, which ran 8 times slower on 1,000,000 values and adds up more rounding. Write $NP.sum($X).

See all rules in the NumPy pack.