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.

This question already has an answer here:

I'm a Mathematica beginner and can't find out a solution to my problem. I have a list of pairs of numbers, for example something like this, but much longer: list={{2., 3.}, {3., 2.}, {5., 4.}, {4., 0.}, {5., 0.}, {5., 0.}, {4., 0.}, {5., 4.}}. And now I need to get only pairs for which some rule is true. For example, I'd like Mathematica to give me pairs {x,y} from the aforementioned list, where x=5 and y is any. So in this case I'd get pairs {5., 4.},{5., 0.},{5., 0.} and {5., 4.}. Is there any way to do this? Thanks :))

share|improve this question

marked as duplicate by Mr.Wizard Jul 28 '13 at 15:06

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers 3

up vote 4 down vote accepted

The command you are looking for is Select. With

list = {{2., 3.}, {3., 2.}, {5., 4.}, {4., 0.}, {5., 0.}, {5.,0.}, {4., 0.}, {5., 4.}}

you can say:

Select[list, #[[1]] == 5. &]

to get those that start with 5.

share|improve this answer
    
Wow, that was quick! :) Thank you very much :)) –  Skumin May 5 '13 at 11:21
    
There are a lot of very powerful functions in Mathematica -- it is worth reading some of the help files (place the cursor on the word and hit F1) to see how they are used. –  bill s May 5 '13 at 11:24
    
This question is relevant mathematica.stackexchange.com/questions/2486/… –  image_doctor May 5 '13 at 13:18

Given:

lis = {{2, 3}, {3, 2}, {5, 4}, {4, 0}, {5, 0}, {5, 0}, {4, 0}, {5, 4}};

then:

Cases[lis, {5, _}]

{{5, 4}, {5, 0}, {5, 0}, {5, 4}}


As an aside, it is better to leave your list with exact symbolic numbers like {4,5} in Mathematica ... and not to convert them into 'approximate' numerical numbers like (4., 5.) ... unless you have a very good reason for doing so.

share|improve this answer

You can also use Pick, for a large list it would be more faster.

list = {{2., 3.}, {3., 2.}, {5., 4.}, {4., 0.}, {5., 0.}, {5.,  0.}, {4., 0.}, {5., 4.}};
Pick[#, #[[All, 1]], 5.] &@list
(*{{5., 4.}, {5., 0.}, {5., 0.}, {5., 4.}}*)


ls = RandomInteger[10, {10^6, 2}];

r1 = Pick[#, #[[All, 1]], 5] &@ls; // Timing
r2 = Select[ls, #[[1]] == 5 &]; // Timing
r3 = Cases[ls, {5, _}]; // Timing
r1 == r2 == r3

(*
{0.062400, Null}
{3.603623, Null}
{1.263608, Null}
True
*)
share|improve this answer

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