# Extracting elements in a list based on conditions [closed]

I have the list

\[ScriptCapitalD] =
{824, 1082, 1135, 1308, 1359, 1372, 1401, 1412, 1601,
1638, 1641, 1674, 1709, 1805, 1947, 2208}

I would like to extract a sublist according to certain defined conditions, such as extracting only values which lie in the range 1000-1500.

What is the best way to do this?

• Select[\[ScriptCapitalD], 1000 <= # <= 1500 &] would do it. But there are many faster ways that already have answers somewhere here... – aardvark2012 Dec 2 '17 at 11:25
• Possible duplicate here – aardvark2012 Dec 2 '17 at 11:34

The standard Mathematica function for that kind of selection, is Select.

data =
{824, 1082, 1135, 1308, 1359, 1372, 1401, 1412, 1601, 1638, 1641, 1674, 1709,
1805, 1947, 2208};
Select[data, Between[#, {1000, 1500}] &]

{1082, 1135, 1308, 1359, 1372, 1401, 1412}

### Update

Between has an operator form, so

Select[data, Between[{1000, 1500}]]

will work and is nicer.

Select has its operator form, too, so one can also write

Select[Between[{1000, 1500}]] @ data
• Can you explain what the operator & does in the argument of Select? – Physkid Dec 2 '17 at 11:38
• @Physkid When writing &, everything to the left of it becomes the body of a function. E.g with plus = # + #2 & then plus[2, 3] evaluates to 5 – Coolwater Dec 2 '17 at 11:43
• @Physkid. Look up Function in the documentation. – m_goldberg Dec 2 '17 at 11:44
• @m_goldberg I like your updated code-cleaner – Physkid Dec 3 '17 at 9:33
sdt = Select[dt, 1000 <= # <= 1500 &]

{1082, 1135, 1308, 1359, 1372, 1401, 1412}
Cases[Clip[lst, {1000, 1500}, {0, 0}], Except[0]]

{1082, 1135, 1308, 1359, 1372, 1401, 1412}

Alternatives, based on Clip:

lst // Pick[#, Clip[#, {1000, 1500}, {0, 0}] // Unitize, 1] &
Clip[lst, {1000, 1500}, {0, 0}] /. 0 -> Nothing

If you selection criteria is always a window (Between[{a,b}]), sorting the data and then doing a binary search may be more efficient. See Windowed binary search