Slice a list of lists?

Jonno jonnojohnson at gmail.com
Wed Sep 8 22:23:35 CEST 2010


On Wed, Sep 8, 2010 at 3:18 PM, Jonno <jonnojohnson at gmail.com> wrote:
> 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:
>>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>>> a[0][2]=3
>>>> a[2][0]=7
>>>>
>>>> but when I try to use fancy indexing to select the first item in each
>>>> list I get:
>>>> a[0][:]=[1,2,3]
>>>> a[:][0]=[1,2,3]
>>>>
>>>> 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[0] means take the first element of a. The first element of a is [1,2,3]
>>> a[0][:] 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[:][0] 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
>>> yourself.
>>>
>>> col = []
>>> for row in a:
>>>    col.append(row[0])
>>>
>>>
>>> You can do this in one line using a list comprehension:
>>> [ row[0] 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?
>
Seems like the simplest way would be:
[row[0] for row in a][::2]



More information about the Python-list mailing list