Steven D'Aprano <[EMAIL PROTECTED]> writes:

> On Wed, 12 Nov 2008 10:08:45 +1100, Ben Finney wrote:
> 
> > Eric <[EMAIL PROTECTED]> writes:
> >> In MATLAB, if  I just want the first, fifth  and eighth element I
> >> might do something like this:
> >> 
> >> b = a([1 5 8]);
> > 
> > Yes: the above code uses magic numbers which convey no semantic
> > meaning, and should instead use *named* elemets of a container. In
> > Python, that's done with a mapping type, which has the built-in
> > type of ‘dict’.
> > 
> > In other words: a list is best for sequences where any item is
> > semantically identical to any other, and you can (for example)
> > re-order all the elements in the list without changing their
> > semantic meaning. If, instead, you want semantic meaning, that's
> > best done via *names*, not magic numbers.
> 
> What the OP is asking for is a generalization of slicing.

I don't think so. (The OP is, of course, welcome to respond to
this or existing requests for clarification of their intent.)

> Given a slice alist[start:end:stride] the indices are given by the
> sequence start+i*stride, bounded by end. It seems to me that the OP
> has asked how to take a slice where the indices are from an
> arbitrary set, possibly given by an equation, but not necessarily.

I think that's exactly what is *not* being asked for, based on the
specific example given. The example was “I just want the first,
fifth, and eighth element”, and the example implementation showed
them with those numeric literals in the code. On that basis I
interpreted the need for *those elements specifically*, for some
semantic reason not yet disclosed.

If, instead, the OP wanted to retrieve “indices … from an arbitrary
set, possibly given by an equation”, I would recommend that *that
equation* be abstracted behind an expression, or even a well-named
function, that would make explicit what the *meaning* of the set was.

I maintain that anything which expresses “retrieve the indices at
these numbers” without saying *in the code* what the meaning of those
numbers is, is to be deprecated in favour of an implementation that
makes the semantic meaning explicit.

And no, before anyone suggests it, an explanatory comment is not
sufficient for this condition: the names and types used should make
clear what the meaning of the expression is. A comment saying *why* is
always appreciated; but if the comment needs to tell me *what* the
code is doing or *how*, the code instead needs to be re-written to be
explicit.

-- 
 \      “Saying that Java is nice because it works on all OSes is like |
  `\     saying that anal sex is nice because it works on all genders” |
_o__)                                                —http://bash.org/ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to