# How to leave only the following strings?

Consider a data having the form

data = {{1,7,4,6},{1,6,4,8},{2,4,9,2},{E,...},{1,4,6,3},{4,4,6,2},{E,...},...}


i.e., some number $$n_{1}$$ of rows followed by row $$\{E,...\}$$, then some number $$n_{2}$$ of rows followed by row $$\{E,...\}$$ and so on.

Could you please tell me how to leave only the last rows before $$\{E,\}$$, i.e. to obtain

subdata= {{2,4,9,2},{4,4,6,2},...}?

• e.g. SequenceCases[data, {x_List, {E, ___}} :> x] – C. E. Apr 22 '19 at 20:27

## 2 Answers

The most idiomatic solution to this problem is, in my opinion, pattern matching (as Sakra has also answered):

SequenceCases[data, {x_List, {E, ___}} :> x]


{{2, 4, 9, 2}, {4, 4, 6, 2}}

But the problem also lends itself to functional solutions, e.g.:

pairs = Partition[data, 2, 1];
If[#[[2, 1]] == E, #[[1]], Nothing] & /@ pairs


{{2, 4, 9, 2}, {4, 4, 6, 2}}

Or in one go:

BlockMap[If[#[[2, 1]] == E, #[[1]], Nothing] &, data, 2, 1]


{{2, 4, 9, 2}, {4, 4, 6, 2}}

Try SequenceCases:

data = {{1, 7, 4, 6}, {1, 6, 4, 8}, {2, 4, 9, 2}, {E, 1, 2, 3},
{1, 4, 6, 3}, {4, 4, 6, 2}, {E, 4, 5, 6}}
SequenceCases[data, {p_, {E, ___}} :> p]


yields

{{2, 4, 9, 2}, {4, 4, 6, 2}}