Simple question about Python lists
Robert Kern
robert.kern at gmail.com
Tue Nov 11 15:44:54 EST 2008
Guilherme Polo wrote:
> On Tue, Nov 11, 2008 at 5:47 PM, Eric <eric.shain at gmail.com> wrote:
>> 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?
>
> MATLAB works with 1-based index, while Python is 0-based, so accessing
> the index number 8 wouldn't be valid with 8 elements here in Python.
>
> Now, to solve your problem you could either use the already suggested
> answer above mine or depending on what you what else you wanna do, you
> will feel more comfortable using numpy.
>
> Supposing you have a array with 8 elements: x = numpy.arange(8)
> To pull out the first, fifth and eighth elements you would do:
> x[numpy.array([0, 4, 7])]
Actually, x[[0,4,7]] will work just as well.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list