# What other methods are there to extract from a list the sublists that contain the same elements as a target list while preserving the order ？

How can we extract from the list

lsts = {{1, 2, 3}, {1, 2, 4}, {1, 8, 3, 7}, {1, 8, 9, 100}, {7, 8, 1, 3}, {1, 7, 3, 8}, {0, 0, 7, 0}, {1, 0, 2, 4}, {1}, {8}, {1, 2}, {9, 8, 5, 8},{1,1,3,3,3,7,7,7,7,8,9,9}}

those sublists that contain the same elements as the specified list

{1, 3, 7, 8}

and have the same number of elements, without altering the original order of the elements in the list

to get the result:

{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}


My approach is as follows:

lsts = {{1, 2, 3}, {1, 2, 4}, {1, 8, 3, 7}, {1, 8, 9, 100}, {7, 8, 1,
3}, {1, 7, 3, 8}, {0, 0, 7, 0}, {1, 0, 2, 4}, {1}, {8}, {1, 2}, {9,
8, 5, 8}, {1, 1, 3, 3, 3, 7, 7, 7, 7, 8, 9, 9}}
target = {1, 3, 7, 8}
result = Select[lsts, Sort@# == Sort@target &]


What other methods can be used to achieve this requirement?

• Sort the target when it is defined target = Sort@{1, 3, 7, 8}; so you don't need to Sort the target for each comparison. Commented Apr 29 at 2:55

list =
{{1, 2, 3}, {1, 2, 4}, {1, 8, 3, 7}, {1, 8, 9, 100},
{7, 8, 1, 3}, {1, 7, 3, 8}, {0, 0, 7, 0},
{1, 0, 2, 4}, {1}, {8}, {1, 2}, {9, 8, 5, 8},
{1, 1, 3, 3, 3, 7, 7, 7, 7, 8, 9, 9}};

target = {1, 3, 7, 8};

Select[list, ContainsExactly @ target]


{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

Cases[list, {OrderlessPatternSequence @@ target}]


{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

via Position using Extract

p = Position[list, x_ /; ContainsExactly[x, target], 1]


{{3}, {5}, {6}}

Extract[list, p]


{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

What other methods can be used to achieve this requirement?

I am sure there are at least 10 different ways to do this. One could be

Select[lsts, Length[Union[#, target]] == Length[#] &]


• Select[lsts,Norm[#]==Norm[target]&]
– Bill
Commented Apr 29 at 3:04

Since you are looking for any permutation of elements, you can do the following:

lsts = {{1, 2, 3}, {1, 2, 4}, {1, 8, 3, 7}, {1, 8, 9, 100}, {7, 8, 1,
3}, {1, 7, 3, 8}, {0, 0, 7, 0}, {1, 0, 2, 4}, {1}, {8}, {1,
2}, {9, 8, 5, 8}, {1, 1, 3, 3, 3, 7, 7, 7, 7, 8, 9, 9}};

elems = {1, 3, 7, 8};
p = Permutations[elems, {Length@elems}];

Select[lsts, MemberQ[p, #] &]


{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

Select[lsts, ContainsAll[#, {1, 3, 7, 8}] && Length[#] == 4 &]