3
$\begingroup$

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

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

f = (1 - Mod[#, 2]) #  &;
f@l1
(* {0, 0, 2, 0, 4} *)
$\endgroup$
-1
$\begingroup$
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

$\endgroup$
  • 3
    $\begingroup$ 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. $\endgroup$ – halirutan Dec 25 '14 at 22:50
  • $\begingroup$ @halirutan very nice! thanks! Didn't know that.. $\endgroup$ – funnyp0ny Dec 26 '14 at 13:09
-1
$\begingroup$
Piecewise[{{#,Mod[#,2]==0},{0,True}},#]&/@ l1
$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – halirutan Dec 25 '14 at 22:47
-1
$\begingroup$

(Assuming you work only with integers in the list)

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

and then

 l2=l1 /. {x_?OddQ -> 0}
$\endgroup$
  • $\begingroup$ This is wrong. If you have sublists this will do all sorts of unpredictable stuff. Consider using Replace[list, rules, {1}] $\endgroup$ – Carlo Jan 24 '15 at 23:43
  • $\begingroup$ @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. $\endgroup$ – mickep Jan 25 '15 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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