# Removing trailing zeros from a list

If I have a list like

list1={2334.,342.,0.,0.,2322.,0.,0.,0.,0.,,,,,,};


it's easy to remove to trailing blanks with Select[list1,NumberQ[#]&], and it's easy to remove all the zeroes, but how do I remove only the trailing zeros? I want to leave the mid-list zeroes in place.

-
There is ImageCrop/ImageTrim, StringTrim but no ListTrim :/ :) –  Kuba Mar 19 '14 at 23:05
@Kuba Don't give SW any ideas for "A new kind of list-manipulation" marketing! –  rm -rf Mar 19 '14 at 23:19

Those trailing blanks are actually Nulls (or "" if you're using strings). The trailing nulls and zeros can be removed with patterns:

list1 /. {h__, (0 | 0. | Null) ...} :> {h}
(* {2334., 342., 0., 0., 2322.} *)

-
I suspect the OP just used the successive commas not to indicate Nulls but rather that there were an unknown number of trailing 0s. –  murray Mar 19 '14 at 14:48
@murray I don't think so, because in the next line they say that they remove the "blanks" with Select and NumberQ... you can't remove the zeros in this manner. –  rm -rf Mar 19 '14 at 14:49
You may be right. I thought perhaps he was referring to the similar situation of deleting trailing "blanks" in a string. –  murray Mar 19 '14 at 14:54
Checking closely, it appears that some of the "Null" entries in my actual data are "", not Null. I adjusted your code accordingly. Thanks. –  Michael Stern Mar 19 '14 at 16:25

If lists are large, something like

list1[[;; (Position[list1, Except[0 |0.| Null], 1][[-1, 1]])]]


should be quite a bit faster, e.g., a quick test on a 50K length list it is over 350X faster than the rule-based solution, and 4X faster than the Take solution.

If the list is "front-loaded" with values (i.e., more wanted than not), using

list1[[;; -Position[Reverse@list1, Except[List | 0 | 0. | Null], 1, 1][[1, 1]]]]


is thousands and hundreds of times faster than rule-based/take posted respectively.

If the lists are precisely the format in your example (desired, chunk of zeroes, chunk of nulls)

Flatten@Split[list1][[;; -3]]


is short, sweet, and very fast.

-