Wolfram Research

FindRanges

Contributed by: Jan Pöschko (Wolfram Research)

Source Notebook

Find continuous ranges in a list of integers

ResourceFunction["FindRanges"][list]

returns ranges of consecutive values for the integers in list.

Details and Options

The list is sorted before detecting ranges. The returned ranges are in ascending order.

Examples

Basic Examples

Find ranges of consecutive values in a list of integers:

In[1]:=
ResourceFunction["FindRanges"][{1, 2, 3, 5, 6, 8}]
Out[1]=

Scope

The given list does not need to be sorted, but will be sorted automatically:

In[2]:=
ResourceFunction["FindRanges"][{2, 8, 3, 1, 5, 6}]
Out[2]=

Properties and Relations

The returned ranges can be joined into the original set of numbers again:

In[3]:=
list = RandomInteger[100, 50]
Out[3]=
In[4]:=
ranges = ResourceFunction["FindRanges"][list]
Out[4]=
In[5]:=
joined = Join @@ Range @@@ ranges
Out[5]=
In[6]:=
joined == Union[list]
Out[6]=

Possible Issues

Non-integer numbers are “swallowed” if they’re between consecutive integers in the list:

In[7]:=
ResourceFunction["FindRanges"][{1, 1.5, 2, 3.2, 4, 8.3}]
Out[7]=

Expressions that are not integers or real numbers constitute their own “range” each:

In[8]:=
ResourceFunction["FindRanges"][{1, 2, x, y, "str"}]
Out[8]=

Resource History