Simple question about Python lists

Robert Kern robert.kern at gmail.com
Tue Nov 11 16:00:28 EST 2008


Eric wrote:
> On Nov 11, 1:51 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>> On Tue, 11 Nov 2008 11:47:53 -0800, Eric 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?
>> b = [a[i] for i in [1, 5, 8]]
>>
>> Ciao,
>>         Marc 'BlackJack' Rintsch
> 
> Thanks! It makes sense, but in this case MATLAB seems easier and no
> less readable. That said, I know better than for a newbie like me to
> question syntax issues.

In my experience, I never do this with lists so there's no optimized syntax for 
it. I do use it very often with numpy arrays, and that does have optimized syntax.

-- 
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