# Find the last element satisfying certain condition in a list

I have a list of numbers and I want to find the last element of it that satisfies certain condition. In this case, the condition is that the number equals 1. I need exactly the position of that element but I don't know how to do it.

I think that this is very basic but I don't know too much about Mathematica. I read the solution given here and tried with

Select[x[i], #=1&]


But it did not work. Anyone knows something?

• Is this a question about Mathematica or Magma? This website is exclusively for Mathematica questions, anything else is considered off topic. Sep 18, 2016 at 22:11
• Last[Position[x,1]] should suffice (I assume you're asking about Mathematica here)...
– ciao
Sep 18, 2016 at 22:11
• Refering to the post you cited: Max@Position[x, _?(# == 1 &)] Sep 18, 2016 at 22:15
• (1) Test equality with Equal (==), not Set (=). (2) It's good to include any error messages you get with the question, usually. Sep 18, 2016 at 22:24
• Since the OP didn't respond for a while, I am going to go ahead and edit out any reference to Magma. That will make the question on-topic, though possibly not useful to the OP if he really meant Magma. Sep 19, 2016 at 9:14

I suppose this will be better in speed as you've said you have a "list of numbers".

Length[list]+1-FirstPosition[Reverse@list,1][[1]]


The usage of FirstPosition may be better in efficiency. :)

Refering to the post you cited:

x = {1, 4, 6, 3, 2, 1, 4, 5, 1, 17};
Max@Position[x, _?(# == 1 &)]


9

The Select approach should use two = intead of one:

Select[x, # == 1 &]


{1, 1, 1}

but doesn't lead you anywhere as it just selects elements from a list that are equal to one by checking... if they are equal to one. You want to find Position of those ones, and specifically find the position of the last one that appears in a list (the last position will also be the biggest number among the list of positions of ones):

Last@Position[x,1]


or

Max@Position[x,1]