Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Is it possible to split a list into two lists at a specific position? The main list is for example:

data={{xa,ya},{xb,yb},{xc,yc},...,{xz,yz}}. 

I want to split this list into two new lists:

data1={{xa,ya},{xb,yb},...,{xi,yi}} 

and

data2={{xj,yj},{xk,yk},...,{xz,yz}} 

at a specific y-value at position i. I was not successful in using Part. Maybe there is another possibility?

share|improve this question

2 Answers 2

up vote 8 down vote accepted

This can be accomplished easily using Part ([[ ]]) and Span (;;), as follows:

data = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}, {xz, yz}};
data[[;; 3]]
data[[4 ;;]]

(* ->
{{x1, y1}, {x2, y2}, {x3, y3}}
{{x4, y4}, {xz, yz}}
*)
share|improve this answer
    
You beat me to it, so I added my answer to yours. –  rcollyer May 5 '12 at 19:34
    
If you don't want Part[], there's always Take[]... –  J. M. May 5 '12 at 19:43

Following up on J.M.'s suggestion,

m = 3;
data1 = Take[data, m]
data2 = Take[data, -(Length[data] - m)]

You might also obtain data2 as follows:

data2 = Complement[data, data1]

I'm uncertain whether the second approach would maintain order invariant if there are identical sublists.

share|improve this answer
2  
Or, perhaps, {Take[#, 3], Drop[ #, 3]} &@data –  TomD May 5 '12 at 22:58
1  
Surprisingly this is faster than Part as recommended by belisarius, and considerably faster than Take/Drop as recommended by Tom. It could also be written: {Take[data, m], Take[data, {m + 1, -1}]} with about the same performance. –  Mr.Wizard May 6 '12 at 0:01
    
I'm surprised it's faster than Take...Drop. –  David Carraher May 6 '12 at 0:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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