# splitting lists into sublists

I have a list from which I would like to create a sublist from this:

lis = {{a,X,b},{c,d,e,X,f},{h,j,X}}


giving:

res = {{a},{c,d,e},{h,j}}


i.e., deleting each X and its following elements from each sublist. Likely asked and answered, any pointers greatly appreciated!

• you could make Thanks Listable and save yourself the /@ :D – Sascha Oct 5 '16 at 19:59

You can use ReplaceAll with an appropriate pattern in such cases

{{a, X, b}, {c, d, e, X, f}, {h, j, X}} /. {begin___, X, end___} :> {begin}


Note the use of named patterns of the BlankNullSequence variety that can stand for any sequence of zero or more expressions

lis = {{a, X, b}, {c, d, e, X, f}, {h, j, X}};
TakeWhile[#, # =!= X &] & /@ lis


{{a},{c,d,e},{h,j}}

From comment by Mr. J.M

First[Split[#, #2 =!= X &]] & /@ lis

• In the same vein: First[Split[#, #2 =!= X &]] & /@ lis – J. M. is in limbo Oct 5 '16 at 19:06
• @J.M. Maybe it deserve as a answer. :) – yode Oct 6 '16 at 7:05
• I'd prefer you edit your answer instead, as it is too similar to yours. – J. M. is in limbo Oct 6 '16 at 7:20

Using Position

lis = {{a, X, b}, {c, d, e, X, f}, {h, j, X}};

#[[1 ;; Position[#, X][[1, 1]] - 1]] & /@ lis

(*  {{a}, {c, d, e}, {h, j}}  *)

• It's worth noting that this one assumes that each sublist does contain an X. – Martin Ender Oct 6 '16 at 12:05