6

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}}
victorshade
  • 83
  • 1
  • 1
  • 3

4 Answers4

11
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

e.doroskevic
  • 5,959
  • 1
  • 13
  • 32
paw
  • 5,650
  • 23
  • 31
5
Pick[list, UnitStep[list - 13], 1]

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

Karsten7
  • 27,448
  • 5
  • 73
  • 134
4

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}

eldo
  • 67,911
  • 5
  • 60
  • 168
3

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}

N.J.Evans
  • 5,093
  • 19
  • 25