2
$\begingroup$

If I have a list of 100 integers, say {1,2...100}, and I wished to delete all elements that are greater than a random integer $n$, what command should I use for this?

For example if $n=5$, how do I operate the original list to get the final list of {1,2,3,4,5}?

$\endgroup$
2
  • 1
    $\begingroup$ Consider using Szabolcs' BoolEval package, available here. One of the functions in the package are available in the function repository, and it could be used with Pick. However, in the package itself there is a function called BoolPick which does exactly what you want with a very nice syntax. $\endgroup$ – C. E. Jan 15 at 12:27
  • 2
    $\begingroup$ You can use Select for this. For example, Select[Range[100], LessEqualThan[5]] $\endgroup$ – LouisB Jan 16 at 21:50
7
$\begingroup$

Are the elements sorted in order? If so:

n = RandomInteger[100];
list = Range[100];
list[[1;;n]]

Otherwise:

Select[list, # <= n &]
$\endgroup$
4
$\begingroup$

It lst is sorted, maybe:

TakeWhile[lst, #<=5&]

Otherwise, maybe:

lst//Pick[#,Clip[# - 5, {0, \[Infinity]}],0]&

Or (thanks to C.E):

lst//Pick[#, UnitStep[5-#], 1]&

Example

 lst=RandomInteger[10,100];
 lst//Pick[#, UnitStep[5-#], 1]&

{3, 2, 3, 4, 4, 4, 3, 4, 4, 2, 1, 4, 0, 4, 5, 2, 4, 1, 0, 2, 4, 3, 5, 3, 0, 0, 0, 4, 1, 4, 3, 4, 5, 1, 4, 0, 1, 5, 0, 0, 1, 2, 5, 1, 3, 3, 2, 4, 3}

$\endgroup$
1
  • 3
    $\begingroup$ The UnitStep function would perhaps be easier to read than this usage of Clip. $\endgroup$ – C. E. Jan 15 at 12:29

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