# how do I multiply list elements by a constant if the element satisfies a condition

I have a list

list={-1,0,1,2,3};


I wish to multiply any element greater than 0.5 by a constant, say 5.0 so that I wind up with

list = {-1,0,5,10,15}


without using a Do loop.

I'm hoping it is crazy simple.

• If[# > .5, 5 #, #] & /@ list?
– kglr
Commented Apr 25, 2017 at 1:22
• Dang, that does it nicely. I'm starting to get the feel for the & /@ construct. Commented Apr 25, 2017 at 1:30
• @TomMozdzen Those are two separate constructions: the ...#...& notation for anonymous functions, and /@ for map. You could use one or the other, or neither as in tom[x_]:=If[x>.5,5x,x];Map[tom,list] Commented Apr 25, 2017 at 2:12
• If you're not yet comfortable with slots (# +&): Function[x, If[x > .5, 5 x, x]] /@ list. Commented Apr 25, 2017 at 3:35

(1 - UnitStep[# - .5]) # + 5 UnitStep[# - .5] # &@list


or

 # (5 UnitStep[# - .5] /. 0 -> 1) &@list


or

If[# > .5, 5 #, #] & /@ list


{-1, 0, 5, 10, 15}

• I like the 3rd one the best, but the 1st two also offer alternative methods. Sure wish there was an example page with a ton of these to get this syntax down pat. Commented Apr 25, 2017 at 1:47

Using Replace with a level spec works as well:

Replace[list, n_ /; 0.5 < n :> 5*n, {1}]
(* {-1, 0, 5, 10, 15} *)


Here, {1} means that you try to replace each expression at level $1$ (and only level $1$) for replacement, and :> is syntactic sugar for RuleDelayed, which means the right hand side (5 * n) is only evaluated after the pattern on the left hand side (n_ /; 0.5) matches, and is evaluated each time it matches.

• Ah - got it, but the condition should be n > 0.5. Also, could you please explain what the {1} does and what the :> does? is the :> an assignment? Commented Apr 25, 2017 at 1:40
• Shorter version... list /. (i_ /; i > 0.5 :> 5 i) (ie, harder to read...)
– kale
Commented Apr 25, 2017 at 3:07
Function[x, If[x > 0.5, 5 x, x], Listable][list]
(* {-1, 0, 5, 10, 15} *)