# (Sparse Array) Can Mathematica delete some of the 0's from a list?

This question continues form Can Mathematica delete some of the 0's from a list?

This time I want to delete zeros before the first positive integer.

I have a list: {0,0,0,1,2,3,0,0,4,5}.

I want Mathematica to return: {1,2,3,0,0,4,5}.

dropper2 = With[{s = SparseArray[#, Automatic, 0]["NonzeroPositions"]}, If[s === {}, {}, #[[;; s[[-1, 1]]]]]] &;

InternalDeleteTrailingZeros@{1, 2, 3, 0, 0, 4, 5, 0, 0, 0}

res0 = InternalDeleteTrailingZeros@test;


returns the wanted results (which was deleting zeros after the integers).

But how can I modify this code into deleting first zeros?

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 Jan 18 '16 at 4:11
• Reverse before & after will do it. Might be better ways, though. – Michael E2 Jan 18 '16 at 4:13
• #[[First@FirstPosition[#, a_?Positive] ;;]] &@{0, 0, 0, 1, 2, 3, 0, 0, 4, 5}. Would this work in general? I think so, unless your list can have negative numbers. – march Jan 18 '16 at 5:02
• Drop[list, FirstPosition[list, _?(# != 0 &)][[1]] - 1] – Hubble07 Jan 18 '16 at 5:09
• Reverse[InternalDeleteTrailingZeros@Reverse[list]] but now I see Michael E2 already suggested it... – bill s Jan 18 '16 at 5:13

list = {0, 0, 0, 1, 2, 3, 0, 0, 4, 5};

list //. {0, a___} :> {a}


{1, 2, 3, 0, 0, 4, 5}

Two ways:

From my comment:

Reverse@InternalDeleteTrailingZeros@
Reverse@{0, 0, 0, 1, 2, 3, 0, 0, 4, 5}
(*  {1, 2, 3, 0, 0, 4, 5}  *)


Using System level functions:

Drop[#, LengthWhile[#, MatchQ[0]]] &[{0, 0, 0, 1, 2, 3, 0, 0, 4, 5}]
(*  {1, 2, 3, 0, 0, 4, 5}  *)

• It can be simplified a bit by using the operator form of MatchQ: Drop[#, LengthWhile[#, MatchQ[0]]] & – Gustavo Delfino Dec 8 '16 at 20:24
• @GustavoDelfino Thanks! – Michael E2 Dec 8 '16 at 21:35
list = {0, 0, 0, 1, 2, 3, 0, 0, 4, 5}

NestWhile[Rest, list, First@# == 0 &]


{1, 2, 3, 0, 0, 4, 5}

Or

While[First@list == 0, list = Rest@list]; list


{1, 2, 3, 0, 0, 4, 5}

If the entries of list are all single-digit integers you can also use

IntegerDigits@FromDigits@{0, 0, 0, 1, 2, 3, 0, 0, 4, 5}
`

{1, 2, 3, 0, 0, 4, 5}