If I have a list like


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.

  • $\begingroup$ There is ImageCrop/ImageTrim, StringTrim but no ListTrim :/ :) $\endgroup$ – Kuba Mar 19 '14 at 23:05
  • 1
    $\begingroup$ @Kuba Don't give SW any ideas for "A new kind of list-manipulation" marketing! $\endgroup$ – 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.} *)
  • $\begingroup$ I suspect the OP just used the successive commas not to indicate Nulls but rather that there were an unknown number of trailing 0s. $\endgroup$ – murray Mar 19 '14 at 14:48
  • $\begingroup$ @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. $\endgroup$ – rm -rf Mar 19 '14 at 14:49
  • $\begingroup$ You may be right. I thought perhaps he was referring to the similar situation of deleting trailing "blanks" in a string. $\endgroup$ – murray Mar 19 '14 at 14:54
  • $\begingroup$ Checking closely, it appears that some of the "Null" entries in my actual data are "", not Null. I adjusted your code accordingly. Thanks. $\endgroup$ – 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.

Block[{Null = 0}, Internal`DeleteTrailingZeros @ Rationalize @ list1]

{2334, 342, 0, 0, 2322}

1. %

{2334., 342., 0., 0., 2322.}


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.