Compare two lists and give 1 and 0 using if command

There are two lists{2,5,9,...} and {natural numbers}. I need to compare it with natural numbers and get a list with 0 and 1 if the number is present in the list, to get {0,1,0,0,1,0,0,0,1,..}

• Question is not clear. Can you give the short list you have and desired output? May 2 '18 at 12:36
• All natural numbers?
– Kuba
May 2 '18 at 13:36
• @Kuba: Are you saying that your computer doesn't have $\aleph_0$ bytes of memory? May 2 '18 at 18:04
• @MichaelSeifert :) I was concerned about the case where the first list contains integers outside of range of the second one.
– Kuba
May 2 '18 at 18:19

SparseArray[List /@ {2, 5, 9} -> 1] // Normal
(* {0, 1, 0, 0, 1, 0, 0, 0, 1} *)

• This is brilliant! I would not have thought of that. May 2 '18 at 14:21
list = {2,5,9,20};
res = ConstantArray[0, Last[list]] (* replace Last by Max if list is not ordered *)
res[[list]] = 1;
res

{0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}

• You could also use ReplacePart, to avoid mutating data. But your approach is probably shorter. May 2 '18 at 13:19

list = {2, 5, 9, 10, 119};
checklist[list_List] := Boole /@ (MemberQ[list, #] & /@ Range[Max[list]])
checklist@list


{0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}

Edit:

Another one, just for fun:

CoefficientList[Plus @@ ((x^#) & /@ list), x]

• That last one is just silly. Kudos. May 2 '18 at 18:03
list = {2, 5, 9};
checklist = RandomInteger[{0, 10}, 10]
(*{9, 0, 2, 2, 0, 0, 8, 7, 0, 4}*)

Map[(If[MemberQ[list, #], 1, 0]) &, checklist]
(*{1, 0, 1, 1, 0, 0, 0, 0, 0, 0}*)