Simple question about Python lists
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Wed Nov 12 02:12:51 CET 2008
On Wed, 12 Nov 2008 10:08:45 +1100, Ben Finney wrote:
> Eric <eric.shain at gmail.com> writes:
>
>> I'm learning Python (while coming from MATLAB). One question I have is
>> that if I have a list with say 8 elements, and I want just a few of
>> them how do I select them out. In MATLAB, if I just want the first,
>> fifth and eighth element I might do something like this:
>>
>> b = a([1 5 8]);
>>
>> I can't seem to figure out a similar Python construct for selecting
>> specific indices. Any suggestions?
>
> 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.
While I see your point, and in practice there are circumstance where I
would agree with you, I don't agree in general.
What the OP is asking for is a generalization of slicing. Slices already
take a stride:
>>> alist = range(20)
>>> alist[2:17:3]
[2, 5, 8, 11, 14]
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. No practical examples
come to mind just off the top of my head, but given that the OP is coming
from a Matlab background, I bet they involve some pretty hairy maths.
Hmmm... let's see now...
http://en.wikipedia.org/wiki/Series_(mathematics)
#Summations_over_arbitrary_index_sets
To put it another way... suppose you have a sequence S given by a list,
and a set of indexes I (perhaps given by a tuple or a set), and you want
to sum the terms of S at those indexes, which mathematicians apparently
have good reason for doing, then you might write in Python:
sum(S[i] for i in I)
But if there was slicing support for arbitrary indexes, you could write:
sum(S[I])
which is apparently what Matlab allows. Standard lists don't support this
slicing generalization, but numpy arrays do.
--
Steven
More information about the Python-list
mailing list