# Use If to create new list from old

I'm trying to use If and AppendTo to create a list by imposing conditions on an initial list. And I'm getting an error that "the expression n cannot be used as a part specification."

X = Tuples[{0, 1}, 4];
B = {};
If[Length[Subsets[X][[n]]] = 2,
AppendTo[B, Mod[Total[Subsets[X][[n]]], 2]], {n, 1, 100}
];


There must be a very simple mistake I'm making here right? Obviously, the elements of Subsets[X] are subsets of the set X. So I'm trying to select those of length 2, and then record that simple expression in a new list.

• There might be better way to do this without using appendto. But first you need to find the = to make it == in Length[Subsets[X][[n]]] = 2 And also you need to use Table. Something like this Table[If[Length[Subsets[X][[n]]] == 2, AppendTo[B, Mod[Total[Subsets[X][[n]]], 2]] ], {n, 1, 100} ] but again, this slow Feb 1, 2020 at 22:55
• Given your initial X, what are you trying to get? And, I presume you have seen that Subsets may take an argument so you could use Subsets[X,{2}] to get all subsets of X with length 2. Feb 2, 2020 at 0:05

Is this what you want?

Mod[Total /@ Subsets[X, {2}], 2]


If you really only want to consider the first 100, you can use MapIndexed instead.

B2 = Mod[Total[Subsets[X, {2}], {2}], 2]


Compare with B

B == B2[[;; Length@B]]


True

where B is obtained from corrected version of your code:

X = Tuples[{0, 1}, 4];
B = {};
Do[If[Length[Subsets[X][[n]]] == 2,
AppendTo[B, Mod[Total[Subsets[X][[n]]], 2]]], {n, 1, 100}];