language design - Why does `Position` by default return a list of lists of positions instead of a simple list of positions?
Position[{1,2,3,4,2,3,4,5},2]
(* Output: {{2},{5}} *)
Why does Position
work this way? I understand this form might be appropriate for, say, different levelspec
s or perhaps other options, but I feel this behavior being default, especially for such a simple example as above, would be unexpected by newcomers.
I'm currently doing [[All,1]]
to get the list I want, but I'm still curious.
Answer
It returns standard position specifications that can be used directly with other functions such as Extract
.
Position specifications work with expressions deeper than a list (e.g. matrix, ragged list, or any arbitrary expression). In this case they must contain more than one index. Thus they take the form of a list.
Standard position specifications are used at least with Extract
, MapAt
, ReplacePart
and Position
. In the general case these functions handle lists of position specifications. Since position specifications themselves are lists too, it is important to be able to distinguish between a single position specification or a list of them. Thus it is absolutely necessary that even one-index one are a (single element) list. Otherwise {1,2}
would be ambiguous: it could represent a single position specification with two indices, or a list of two one-index position specifications.
Having a consistent standard form for position specifications is thus useful and makes it easy to write general code that works fine in edge cases too.
Of course you are right that having {k}
instead of k
for the most common use case seems inconvenient. I believe that is one reason why we also have Part
in addition to extract. Part
uses a different syntax for part specifications and is more convenient for standard array indexing.
In general, you would use Part
when indexing directly, and you would use Extract
with the output of Position
.
Comments
Post a Comment