Slice a list of lists?
benjamin.kaplan at case.edu
Wed Sep 8 21:11:51 CEST 2010
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 ]
More information about the Python-list