Skip to main content
4 of 6
added 23 characters in body
Sjoerd Smit
  • 25.7k
  • 51
  • 85

Here are two methods that are quite fast for flat lists (you can flatten arrays to test at deeper levels):

const = ConstantArray[1, 100000]; nonconst = Append[const, 2]; 

Using CountDistinct (or CountDistinctBy):

CountDistinct[const] === 1 CountDistinct[nonconst] === 1 

True

False

Based on pattern matching:

MatchQ[const, {Repeated[x_]}] MatchQ[nonconst , {Repeated[x_]}] 

True

False

The MatchQ approach can be generalized for deeper arrays using Level without having to Flatten everything:

constTensor = ConstantArray[1, {5, 5, 5}]; MatchQ[Level[constTensor, {ArrayDepth[constTensor]}], {Repeated[x_]}] 

True

Timings

CountDistinct[const] // RepeatedTiming MatchQ[const, {Repeated[x_]}] // RepeatedTiming 

{0.00021, 1}

{0.0051, True}

MatchQ has the advantage that it short-circuits when a list doesn't match:

nonconst2 = Prepend[const, 2]; MatchQ[nonconst2, {Repeated[x_]}] // RepeatedTiming 

{6.*10^-7, False}

Sjoerd Smit
  • 25.7k
  • 51
  • 85