For a list of strings (or other elements):

t1 = Table[RandomChoice[CharacterRange["A", "E"]], 20]
{"D", "A", "B", "C", "A", "A", "E", "C", "C", "C", "B", "A", "A", \
"C", "B", "D", "D", "A", "B", "C"}

I want to split the list starting at a certain symbol (say "B"):

t2 = Split[t1, (#2 != "B") &]

{{"D", "A"}, {"B", "C", "A", "A", "E", "C", "C", "C"}, {"B", "A", "A",
   "C"}, {"B", "D", "D", "A"}, {"B", "C"}}

Now I define a function (so that I can further fork sublists starting at "C")

f[x_List, s_String] := Split[x, (#2 != s) &]

f[#, "C"] & /@ t2
{{{"D", "A"}}, {{"B"}, {"C", "A", "A", 
   "E"}, {"C"}, {"C"}, {"C"}}, {{"B", "A", "A"}, {"C"}}, {{"B", "D", 
   "D", "A"}}, {{"B"}, {"C"}}}

To get the same output, the following works too:

Split[# , (#2 != "C") &] & /@ Split[t1, (#2 != "B") &]


  1. seeking a better implementation of the pure function above or better still ...
  2. I want to write a function to which I can provide a main list such as t1 and a list of tokens {"B","C"} to achieve the same effect, perhaps using Fold that I can't figure out.

Thanks in advance for your help.


1 Answer 1


You could use "SplitBy" like the following:

t1 = Table[RandomChoice[CharacterRange["A", "E"]], 20]

fl = 1;
fun[c_] := (If[# == c, ++fl]; fl) &
SplitBy[t1, {fun["B"], fun["C"]}]

enter image description here


Your Answer

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

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