Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get every other item in a list

I have a list in Mathematica, and I am trying to obtain every other number in the list and store it as a new list.

Currently I have

ReadList["file",Number]

which reads out the entire list, { x1, x2, x3, x4, ... }; I just want to pick out every other number and store it in a new list, e.g. { x1, x3, x5, ... }.

How to do that?

like image 691
user1200775 Avatar asked Feb 09 '12 22:02

user1200775


3 Answers

Try:

  yourlist = {a, b, c, d, e, f, g, h};
 (* use Span: search for  Span or ;; in Documentation Center *)
 everyotheritemlist = yourlist[[1 ;; -1 ;; 2]];
 (* or use Take *)
 Take[yourlist, {1, -1, 2}]

Both give:

 {a,c,e,g}    
like image 83
kglr Avatar answered Oct 19 '22 08:10

kglr


For tasks like that there are always dozens of creative ways to do it in Mathematica. kguler already gave you the canonical ways, but here's another one:

Partition[yourlist, 2]\[Transpose][[1]]

(*
==> {a, c, e, g}
*)

By the way: There's a dedicated Mathematica Stackexchange site at https://mathematica.stackexchange.com/. The Mathematica community is more and more moving in that direction, so you may want to join us there as well.

like image 33
Sjoerd C. de Vries Avatar answered Oct 19 '22 07:10

Sjoerd C. de Vries


One more way:

First /@ ReadList["test.dat", {Number, Number}]
like image 1
Mr.Wizard Avatar answered Oct 19 '22 08:10

Mr.Wizard