Message Boards Message Boards

GROUPS:

Use "While" loop to get parts of a list?

Posted 11 days ago
82 Views
|
3 Replies
|
2 Total Likes
|

I am trying to cut a list into several consecutive lists. For example, if I had a 10 element list:{1,2,3,4,5,6,7,8,9,10} I would want to cut it into 5 consecutive 2 element lists:{1,2},{3,4},{5,6},{7,8},{9,10}. I am trying to do this with a "While" loop as follows but I am not being able to get this to work. I have searched the knowledge base and documentation and it seems like I am doing it correct but obviously not because it does not work. Can someone tell me what I am doing wrong?

Below is what I have tried without success. Essentially nothing happens when I try to execute the code.

seq = {52.000, 52.289, 39.000, 
   0.000, -10.121, -19.000, -22.000, -28.203, -18.000, -6.000, -5.615,
    0.000, 0.000, 1.770, 2.000, 4.000, 3.903, 
   2.000, -4.000, -3.729, -3.000, 4.000, 20.378, 20.000, 47.000, 
   74.958, 58.000, 54.000, 68.563, 40.000, 17.000, 16.861, 
   2.000, -4.000, -11.492, -11.000, -20.000, -21.798, -14.000, 6.000, 
   7.932, 10.000, -1.000, -4.688, -7.000, -7.000, -10.321, -7.000, \
-7.000, -10.321, -7.000, -7.000, -10.321, -7.000, -7.000, -10.321, \
-7.000, -7.000, -10.321, -7.000};
n = 1; m = 5; While[n < Length[seq]/5, Part[seq, n ;; m]; n += 5; m += 5]
3 Replies
Posted 11 days ago

I think Partition may do what you want without needing a while loop.

Posted 11 days ago

Partition did the trick. Thank you!

Posted 11 days ago
list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Partition[list, 2]
(* {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}} *)
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract