On Wed, Sep 8, 2010 at 2:55 PM, Jonno <jonnojohn...@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 ] > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list