Slice a list of lists?
jonnojohnson at gmail.com
Wed Sep 8 22:18:56 CEST 2010
On Wed, Sep 8, 2010 at 3:06 PM, Jonno <jonnojohnson at gmail.com> wrote:
> On Wed, Sep 8, 2010 at 2:11 PM, Benjamin Kaplan
> <benjamin.kaplan at case.edu> wrote:
>> On Wed, Sep 8, 2010 at 2:55 PM, Jonno <jonnojohnson at gmail.com> wrote:
>>> I know that I can index into a list of lists like this:
>>> but when I try to use fancy indexing to select the first item in each
>>> list I get:
>>> Why is this and is there a way to select [1,4,7]?
>> It's not fancy indexing. It's called taking a slice of the existing
>> list. Look at it this way
>> a means take the first element of a. The first element of a is [1,2,3]
>> a[:] means take all the elements in that first element of a. All
>> the elements of [1,2,3] are [1,2,3].
>> a[:] means take all the elements of a. So a[:] is [[1,2,3],[4,5,6],[7,8,9]].
>> a[:] means take the first element of all the elements of a. The
>> first element of a[:] is [1,2,3].
>> There is no simple way to get [1,4,7] because it is just a list of
>> lists and not an actual matrix. You have to extract the elements
>> col = 
>> for row in a:
>> You can do this in one line using a list comprehension:
>> [ row for row in a ]
> Thanks! (to Andreas too). Totally makes sense now.
Now if I want to select the first item in every 2nd item of list a
(ie: [1,7]) can I use ::2 anywhere or do I need to create a list of
indices to use in a more complex for loop?
More information about the Python-list