Skip to content

numpy/where-tuple-length

Rule where-tuple-length
Pack NumPy
Severity error
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

np.where with one argument returns a tuple with one array per dimension, so its length counts dimensions and not matches. Use np.count_nonzero.

matches = len(np.where(z > 0))
matches = np.count_nonzero(z > 0)

The rule reports len(np.where(z > 0)), len(np.nonzero(z)) and if np.where(z > 9):, because np.where with one argument returns a tuple with one array per dimension. The length of the tuple is the number of dimensions, and the tuple is always true.

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.count_nonzero(z > 0).

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

$F returns a tuple with one array per dimension, so its length is the number of dimensions and not the number of matches. Write $NP.count_nonzero($C).

Browse the other rules of the NumPy pack.