# List Manipulation Via Conditionals

I'm trying to convert one list to another by applying a condition on the list's elements. But I can't figure out how to do this in mathematica's language. Python example below

l1 = [0, 1, 2, 3, 4]
l2 = []
for i in l1:
if i % 2 == 0:
l2.append(i)
else:
l2.append(0)

• {0, 1, 2, 3, 4} // Select[Mod[#, 2] == 0 &] (* {0, 2, 4} *) – alancalvitti Nov 25 '14 at 17:06
• @alancalvitti this way you miss appending zeros – funnyp0ny Nov 25 '14 at 17:40
• @funnypony, thanks. {0, 1, 2, 3, 4} // Map[If[Mod[#, 2] == 0, #, 0] &] – alancalvitti Nov 25 '14 at 18:52
• @alancalvitti that's nice! you can also freely remove Map, which seems unnecessary – funnyp0ny Nov 25 '14 at 20:01

For the specific condition in OP's example, you can also use

f = (1 - Mod[#, 2]) #  &;
f@l1
(* {0, 0, 2, 0, 4} *)

Table[If[Mod[l, 2] == 0, l, 0], {l, 0, 4}]


or

Table[If[Mod[l1[[i]], 2] == 0, l1[[i]], 0], {i, Length@l1}]


for arbitrary list l1

• What about Table[If[Mod[l, 2] == 0, l, 0], {l, l1}] for arbitrary l1? Remember that you can simply iterate through l1 with this, when you don't need the index of the current element. – halirutan Dec 25 '14 at 22:50
• @halirutan very nice! thanks! Didn't know that.. – funnyp0ny Dec 26 '14 at 13:09
Piecewise[{{#,Mod[#,2]==0},{0,True}},#]&/@ l1

• Why is your Piecewise so complicated? You only need one condition which is Mod[#,2]==0. If this is not satisfied, that you can use the default value. So either Piecewise[{{#, Mod[#, 2] == 0}}, 0] & or even shorter Piecewise[{{#, Mod[#, 2] == 0}}] & should be enough. – halirutan Dec 25 '14 at 22:47

(Assuming you work only with integers in the list)

 l1={0,1,2,3,4}


and then

 l2=l1 /. {x_?OddQ -> 0}

• This is wrong. If you have sublists this will do all sorts of unpredictable stuff. Consider using Replace[list, rules, {1}] – Carlo Jan 24 '15 at 23:43
• @Carlo I don't claim that to be a universal solution. I just claim that it works for the list that Erik asks about... Thanks for your clarification, though. – mickep Jan 25 '15 at 6:53