4

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}.

From ciao's answer

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

Internal`DeleteTrailingZeros@{1, 2, 3, 0, 0, 4, 5, 0, 0, 0}

res0 = Internal`DeleteTrailingZeros@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 04:11
  • You can format inline code and code blocks by selecting the code and clicking the {} button above the edit window. The edit window help button ? is also useful for learning how to format your questions and answers. You may also find this this meta Q&A helpful – Michael E2 Jan 18 '16 at 04:12
  • 3
    Reverse before & after will do it. Might be better ways, though. – Michael E2 Jan 18 '16 at 04:13
  • 1
    #[[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 05:02
  • 3
    Drop[list, FirstPosition[list, _?(# != 0 &)][[1]] - 1] – Hubble07 Jan 18 '16 at 05:09
  • 4
    Reverse[Internal`DeleteTrailingZeros@Reverse[list]] but now I see Michael E2 already suggested it... – bill s Jan 18 '16 at 05:13

3 Answers3

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

Using ReplaceRepeated:

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

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

corey979
  • 23,947
  • 7
  • 58
  • 101
4

Two ways:

From my comment:

Reverse@Internal`DeleteTrailingZeros@
  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}  *)
Michael E2
  • 235,386
  • 17
  • 334
  • 747
1
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}

kglr
  • 394,356
  • 18
  • 477
  • 896