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?
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}
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.
One more way:
First /@ ReadList["test.dat", {Number, Number}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With