1
$\begingroup$

Imagine I have a list of the type

Lst = {{1,0,1,1},{4,0,1,1}, {1,1,0,0},{2,1,1,1},{0,0,0,1}}

I want to select only those sublists that only contain elements 0 or 1. For example for the above list the reduced list which I want is

IWantThis = {{1,0,1,1},{1,1,0,0},{0,0,0,1}}

Motivation for this is the given situation describes spinless fermions or spin 1/2 objects.

$\endgroup$
1
  • $\begingroup$ If the order doesn't matter then BitAnd[Lst, 1] ⋂ Lst does it $\endgroup$
    – Coolwater
    Feb 27, 2019 at 12:21

2 Answers 2

4
$\begingroup$

To filter a list

list = {{1, 0, 1, 1}, {4, 0, 1, 1}, {1, 1, 0, 0}, {2, 1, 1, 1}, {0, 0, 0, 1}};

you can use Select like this:

Select[list, ContainsOnly[{0, 1}]]
(* {{1, 0, 1, 1}, {1, 1, 0, 0}, {0, 0, 0, 1}} *)

This should work with Mathematica 10.2+.

$\endgroup$
2
  • $\begingroup$ OK. Thanks a lot $\endgroup$ Feb 27, 2019 at 11:50
  • 1
    $\begingroup$ In earlier versions, use Cases[] instead: Cases[list, {(0 | 1) ..}]. $\endgroup$ Mar 1, 2019 at 9:30
2
$\begingroup$

Using Select and Union.

Lst = {{1,0,1,1},{4,0,1,1}, {1,1,0,0},{2,1,1,1},{0,0,0,1}};
Select[Lst, Union[#] == {0, 1} &]

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

I have used Unionspecifically, because it sorts out the list after removing duplicates unlike DeleteDuplicates.

$\endgroup$
1
  • $\begingroup$ Ok thanks a lot $\endgroup$ Feb 27, 2019 at 11:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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