Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

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

2 Answers 2

up vote 3 down vote accepted

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.} *)
share|improve this answer
    
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 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 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 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 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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