6

I am trying to avoid using For because I heard that For is not cool in functional programming. Below is a problem that the first idea came to my mind is using For. How can I change this into a code using Table or Range or something else?

What the code does is to extract the elements in a list ls which satisfies certain condition into a new list lsNew.

ls = RandomInteger[20, 1000];
lsNew = {};
For[i = 1, i <= Length[ls], i++,
  If[ls[[i]] < 6, lsNew = Append[lsNew, ls[[i]]]]]
lsNew
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
an offer can't refuse
  • 1,745
  • 12
  • 23

3 Answers3

10

Have a look at Select.

lsNew = Select[# < 6 &]@ls
Edmund
  • 42,267
  • 3
  • 51
  • 143
3

OK, the related post I linked above may be too long, so let me extract the relevant part:

Pick[#, UnitStep[# - 6], 0] &@ls

Just for fun, here's a somewhat strange solution:

ls /. $_ /; $ >= 6 :> (## &[])
xzczd
  • 65,995
  • 9
  • 163
  • 468
3

Although Select is the classical Mathematica function for doing what you ask, in V10.2 or later one can map an If expression (for some a more natural way to express the problem) and get the desired results.

SeedRandom[42]; data = RandomInteger[20, 100];
If[# < 6, #, Nothing] & /@ data

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

This is likely to run slower the Select, but will run much faster than a For-loop.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257