Position of the first nonzero number

I want to know is there any one line code to find position of first nonzero number without calculating position of all non zero numbers. For example,

A = {0, 0, 0, 1, -2, -1, 0};
First[Flatten[Position[A, _?(# != 0 &)], 1]]


will give me position of first non zero number. But first it calculate position of all non zero number. Is there any way to stop position function when it found first non zero number?

• FirstPosition[A, _?(# != 0 &)]  – OkkesDulgerci May 2 '19 at 19:21

9 Answers

You can specify number of object to return in Position. For example,

list = RandomInteger[{-5, 5}, 100000];
Position[list, _?(# != 0 &), 1, 1] // AbsoluteTiming


{0.003050, {{1}}}

Position[list, _?(# != 0 &)] // First // AbsoluteTiming


{0.138709, {1}}

SeedRandom[1];
LengthWhile[RandomInteger[{-5, 5}, 100000], # == 0 &] + 1
(* 1 *)

• you mean by this? LengthWhile[list, # == 0 &] + 1 – halmir Oct 4 '13 at 19:03
• @halmir yes, I corrected it while you were writing the comment :) – Dr. belisarius Oct 4 '13 at 19:04

We can use SparseArray. It computes all the positions, but it's a bit faster than Position, esp. on packed arrays, since Position unpacks a packed array.

First @ SparseArray[packedarray]["NonzeroPositions"]


or

First @ SparseArray[DeveloperToPackedArray @ unpackedlist]["NonzeroPositions"]


Timings on ten random lists:

SeedRandom[1];
n = 10;
list = RandomChoice[{0.9, 0.1} -> {0, 1}, {n, 100000}];
packedlist = DeveloperToPackedArray @ list;

Table[
First @ SparseArray[DeveloperToPackedArray @ list[[i]]]["NonzeroPositions"],
{i, n}] // AbsoluteTiming
Table[
Position[list[[i]], _?(# != 0 &), 1, 1],
{i, n}] // AbsoluteTiming

Table[
First @ SparseArray[packedlist[[i]]]["NonzeroPositions"],
{i, n}] // AbsoluteTiming
Table[
Position[packedlist[[i]], _?(# != 0 &), 1, 1],
{i, n}] // AbsoluteTiming


{0.007372, {{15}, {28}, {4}, {20}, {13}, {2}, {8}, {7}, {42}, {9}}}
{0.009183, {{{15}}, {{28}}, {{4}}, {{20}}, {{13}}, {{2}}, {{8}}, {{7}}, {{42}}, {{9}}}}

{0.005098, {{15}, {28}, {4}, {20}, {13}, {2}, {8}, {7}, {42}, {9}}}
{0.024295, {{{15}}, {{28}}, {{4}}, {{20}}, {{13}}, {{2}}, {{8}}, {{7}}, {{42}}, {{9}}}}

Compiled

It's rather straightforward in an imperative paradigm:

firstnzp = Compile[{{list, _Integer, 1}},
Do[If[list[[i]] != 0, Return[i]], {i, Length@list}],
RuntimeOptions -> "Speed"
]


And fast:

Table[firstnzp @ list[[i]], {i, n}] // AbsoluteTiming


{0.004164, {15, 28, 4, 20, 13, 2, 8, 7, 42, 9}}

While this certainly isn't a contender for speed, patterns are fun:

A /. {z : Longest[(0 | 0) ...], ___} :> Length@{z} + 1


Just for fun:

ArrayRules[list][[1, 1, 1]]


Yet another compiled function:

firstnzp2 = Compile[{{list, _Integer, 1}},
Module[{n = 0}, While[list[[++n]] == 0]; n],
CompilationTarget -> "C", RuntimeOptions -> "Speed"];


The speed is the same as Michael's compiled code after addition CompilationTarget -> "C".

Or one-liner:

1 + Total@UnitStep[-Accumulate@Unitize[list]]


Comparing:

Position[s, e_ /; e != 0] // Trace

Position[s, e_ /; e != 0, 1, 1] // Trace

The number of matched positions to be found at certain levels can be specified, then Position, searching left to right, stops as soon as it finds that many.

If you are interested in manual solution, this might be helpful as well.

    f[x_] := (If[x > 0, Return[Position[A, x][[1, 1]]]]; x)

sparr = SparseArray[{{1, 400} -> 2, {1, 90000} -> 2}]
A = Normal[sparr][[1]];
Catch[Table[If[f[A[[i]]] > 0, Throw[f[A[[i]]]], f[A[[i]]]], {i, Length[A]}]]


400 (Timing 0.06 Sec)

sparr = SparseArray[{{1, 90000} -> 2}]
A = Normal[sparr][[1]];
Catch[Table[If[f[A[[i]]] > 0, Throw[f[A[[i]]]], f[A[[i]]]], {i, Length[A]}]]


90000 (1.11 Sec)

Here is a simpler method to get the position of the first nonzero element:

Position[A, DeleteCases[A, 0][[1]]][[1, 1]]  (* Single Line *)


Here is how it works:

firstNonZeroElement =  DeleteCases[A, 0][[1]] (* Returns value of first non-zero element *)
Position[A, firstNonZeroElement] (* Finds positions of all occurances of firstNonZeroElement *)
First[Position[A, firstNonZeroElement]][[1]] (* Selects the first one *)

• I don't think that this is what OP asked for: DeleteCases[A, 0][[1]] messes around with the whole list A and this leads to a timing that is consideraly higher than halmir's. – Henrik Schumacher May 21 '19 at 1:10
• You are right about timing, this might not be the best. A remains unchanged. – axsvl77 May 21 '19 at 10:19
• The benefit of this method is that it may be understandable for a new Mathematica user – axsvl77 Aug 12 '19 at 2:32