Applying If[] to a list

So I have a list of values

truthValues = {True, True, False}

and for each element of the list, I would like to return a different value if that element is true or not. So I would like to return this array if everything is true:

trueList = {1, 1, 1}

And this array if everything is false:

falseList = {0, 0, 0}

So for the list of values above, I would like to return

{1, 1, 0}

But the If[] function doesn't appear to support this directly, and the Apply function doesn't seem to do the trick either. Ideas?

• Or if you need other return values than 0/1, you could try truthValues /. {True -> something, False -> somethingElse} – Coolwater Sep 26 '16 at 19:12

It's simplest to use Map like this:

If[#, 1, 0] & /@ {True, True, False}

{1, 1, 0}

or Boole is straightforward as it's designed for such purposes:

Boole @ {True, True, False}

{1, 1, 0}

Boole will return 0/1, but if you want something different to work with later, use If.

• For your 1st two code segments, I'm having them evaluate to {True, True, False}. The map works perfectly, though. – Jordan Sep 26 '16 at 20:30
• Indeed; I must've mixed some outputs while copying, sorry for that. I edited not to make confusion. Nevertheless, Map is the usual way when you want to use If. – corey979 Sep 26 '16 at 20:44
MapThread[ If , {{True, True, False}, {1, 2, 3}, {4, 5, 6}}]

{1,2,6}

or per comment:

Thread@If[{True, True, False}, {1, 2, 3}, {4, 5, 6}]

{1,2,6}

with a caveat the Thread form only works if you use an explicit list argument. For example you can't do this:

falselist = {4, 5, 6};
Thread@If[{True, True, False}, {1, 2, 3}, falselist]

{1, 2, {4, 5, 6}}

resulting from If's HoldRest attribute. ( you could do Thread@If[{True, True, False}, {1, 2, 3}, Evaluate@falselist] )

• And again you came up with a better version than mine. Also the first time i've seen MapThread being really usefull. Again: thanks ^^ – Julien Kluge Sep 26 '16 at 20:35
• Even Thread should work here – LLlAMnYP Sep 27 '16 at 8:44
• @LLlAMnYP, yes.. added to the answer. – george2079 Sep 27 '16 at 15:27
• Actually, I take that back, because If's HoldRest attribute can break the intended behavior: Thread[If[truthValues, trueList, falseList]] evaluates only truthValues at first and ends up giving a list of 3 results (in OPs example {trueList, trueList, falseList}. – LLlAMnYP Sep 28 '16 at 9:41

Assuming everything can be in your false and true list:

truthValues={True,True,False}
trueList={a,b,c}
falseList={x,y,z}
• the straightforward way is to use Table to "iterate" over your lists
Table[If[truthValues[[i]],trueList[[i]],falseList[[i]]],{i,1,Length[truthValues]}]

{a,b,z}

• a better way is to use Apply (which even matches your question "applying [...]"):
If[#1,#2,#3]&@@@Transpose[{truthValues,trueList,falseList}]

{a,b,z}

• even just do If @@@ Transpose.. for the last case. – george2079 Sep 26 '16 at 20:26