Message Boards Message Boards

0
|
7602 Views
|
4 Replies
|
4 Total Likes
View groups...
Share
Share this post:

FirstPosition[ls, SelectFirst[ls, # >= 1 &]]

Posted 10 years ago

Is there an efferent way to do this?

ls = {.5, 1.0, 2.0};
FirstPosition[ls, SelectFirst[ls, # >= 1 &]]
POSTED BY: Jeff Burns
4 Replies

If you know the position of something in a Mathematica expression then you can extract it from that expression using Part (the First in the last line here is because FirstPosition returns a list containing the position)

ls = {.5, 1.0, 2.0};
pos = FirstPosition[ls, _?(# >= 1 &)];
ls[[First[pos]]]

By the way, the

ls = {.5, 1.0, 2.0};
pos = FirstPosition[ls, _?(# >= 1 &)]

returns what your original code does so that's why I didn't then extract the value.

POSTED BY: David Reiss

The second argument of FirstPosition is a pattern. So there is no need to first find the item to explicitly use as that pattern. You can specify the pattern itself defined as asking about the pure funcition's value (True or False) as in:

FirstPosition[ls, _?(# >= 1 &)]
POSTED BY: David Reiss
Posted 10 years ago

Thanks for the reminder that the argument is a pattern but the original search is for values. Using the output of SelectFirst sets the search up for an exact match. So the naive way to find the last element won't work.

ls = {.5, 1.0, 2.0};
Position[ls, SelectFirst[ls, # >= 1 &]][[-1]]
{2}

Neat way to force the evaluation. _?(# >= 1 &) I think Mathematica needs a LastPosition function as much as it needs FirstPosition.

POSTED BY: Douglas Kubler

If you are wanting to find the position of the first element of the list that is greater than 1, then:

Position[(*in list*)ls, (*of first element *)Select[ ls, # >(*greater than*)1&, 1(*EndSelect*)][[1]] (*EndPosition*)]
POSTED BY: Isaac Abraham
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