NumPy: Trimming the zeros at the ends
academiamastertrader.com.br offers learning material from Academia Master Trader. For English-speaking readers in the US Virgin Islands, from Charlotte Amalie to Cruz Bay, we present this example: the trim_zeros function in NumPy. It removes the zeros at the start and at the end of a list and keeps everything between them. We apply it to a list of seven values.
Run the example
We set up a list of seven values with zeros at both ends and call the function.
import numpy as np
print(np.trim_zeros(np.array([0, 0, 2, 3, 0, 4, 0])))
The result shown is [2 3 0 4]. The two zeros at the start and the one at the end leave, and the zero between 3 and 4 stays.


academiamastertrader.com.br: more learning material from Academia Master Trader complements this example.
Understand the result
The documentation describes trim_zeros as a helper that trims the leading and trailing zeros of a list, keeping the order of what remains. Zeros between values stay in place.
The result is easy to check: read the list from both ends and stop where the values begin. What remains keeps its order. Lists like this appear in daily counts, for example ferry trips between Charlotte Amalie and Cruz Bay, where quiet hours at the ends can be trimmed.
Place the result
The program keeps the input as it is. It returns a new value or a new list. Each example shows the rule at work on its own values.
To verify the result, recalculate each entry by hand and compare it with the display. Each value can be confirmed mentally.
Longer lists follow the same rule. The function then computes each entry separately and returns a list of the same length.
Naming the values makes the sequence readable: first set the lists, then call the function, then read the display. Each step is verified separately.
Single numbers instead of lists are also allowed. The function then returns exactly one number, following the same calculation rule as for each entry of a list.
Anyone who needs several calculations of this kind in a row can chain the calls. The result of the first call then serves as input to the next, and each intermediate step stays readable.
Small examples are especially good for practice, because you can estimate the result in advance. Whoever estimated well understands the rule behind the function.
Comparing the three entries shows the benefit: the display summarizes the behavior of the list in a few characters. Whoever has understood the rule once reads such displays at a glance and immediately recognizes whether a value is plausible.
In daily work: when passing on results, preferably cite input and output side by side. That way every reader can redo and confirm the step themselves.
The practical reading rule: read trim_zeros as trimming the zeros at the ends and confirm the remaining order by hand.
Academia Master Trader explains numerical tools with examples you can check. More learning material is at academiamastertrader.com.br and via Aprenda.