5
$\begingroup$

If I have a list like:

list = {23,21,18,15,13,12,10,9,8,7,7,5}

How can I remove numbers from that list so that no number less than 13 is on it without hardcoding, so if the list were different it would still remove any numbers less than 13?

I tried using the position like:

position = Position[list, 2]
listNew = list[[1;;position]]

It doesn't work because position's output is

{{10}}
$\endgroup$
  • $\begingroup$ closely related 180 $\endgroup$ – Kuba Nov 19 '15 at 17:57
  • 2
    $\begingroup$ A built-in function to remove elements from a list would be DeleteCases. This should evaluate to what you are looking for: DeleteCases[list,_?(# < 13 &)]. $\endgroup$ – user31159 Nov 19 '15 at 18:23
  • 1
    $\begingroup$ What about marking this as a duplicate of 24167 $\endgroup$ – Kuba Nov 19 '15 at 18:32
9
$\begingroup$
list = {23, 21, 18, 15, 13, 12, 10, 9, 8, 7, 7, 5};
Select[list, # >= 13 &]

{23, 21, 18, 15, 13}

Reference:
Select
Selecting parts of Expression with Function

| improve this answer | |
$\endgroup$
5
$\begingroup$
Pick[list, UnitStep[list - 13], 1]

$\ ${23, 21, 18, 15, 13}

| improve this answer | |
$\endgroup$
4
$\begingroup$

If you want to use Position

pos = Flatten @ Position[list, _?(# >= 13 &)]

{1, 2, 3, 4, 5}

list[[pos]]

{23, 21, 18, 15, 13}

Since your list is ordered it's more efficient to write

pos = First@FirstPosition[list, _?(# <= 13 &)]

5

list[[;; pos]]

{23, 21, 18, 15, 13}

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ ...but if you like patterns so much, then use Cases[] instead. ;) $\endgroup$ – J. M.'s discontentment Nov 19 '15 at 17:52
3
$\begingroup$

Replacement rules are another option - just for exposure to new ideas. This will be slow on big lists.

list = {23,21,18,15,13,12,10,9,8,7,7,5}
newList = list/. _?(# < 13 &)->Sequence[]

gives {23, 21, 18, 15, 13}

| improve this answer | |
$\endgroup$
  • 3
    $\begingroup$ Since 10.2 one can use Nothing instead of Sequence[]. $\endgroup$ – gwr Nov 19 '15 at 19:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.