# How to apply a piecewise function to a list? [closed]

I have created this code:

xn = {4, -4, 4, -4}
f[x_] = Piecewise[{{Sqrt[x], x >= 0}, {Sqrt[-x], x < 0}}]
f[xn]


With this code I would expect as a result:

{2,2,2,2}

But that's not what I get.

Question 1 - Why don't I get the desired result?

Question 2 - How to get the desired result?

• f/@xn or SetAttributes[f, Listable]... – ciao Jul 12 '16 at 21:09
• What is the difference between f/@xn and f[xn]? – GambitSquared Jul 12 '16 at 21:10
• Why not use Sqrt[Abs[x]]? – J. M. will be back soon Jul 12 '16 at 21:11
• "What's the difference" - in your notebook, highlight the /@ and press F1, so that you can answer your own question. – J. M. will be back soon Jul 12 '16 at 21:11
• Well, you didn't say that you were going to differentiate the blasted thing… – J. M. will be back soon Jul 12 '16 at 21:58

Your code shows two elementary misunderstandings. First, you do not understand the difference between Set and SetDelayed. Second, you do not understand what a Listable function is. Yet both these concepts are fundamental to working with Mathematica.
xn = {4, -4, 4, -4};