Slice a list of lists?

Andreas Waldenburger usenot at geekmail.INVALID
Wed Sep 8 15:08:11 EDT 2010


On Wed, 8 Sep 2010 13:55:50 -0500 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:
Let me write out in words what you're doing, and it should become clear:

> a[0][:]=[1,2,3]
Here you're making a list of all elements of the first element of a.

> a[:][0]=[1,2,3]
> 
And here you're selecting the first element of all elements of a.

Huh. Not quite as clear as I hoped. But ponder on this for a few
moments. It'll dawn on you eventually.


> Why is this and is there a way to select [1,4,7]?

zip(*a)[0]

(or rather list(zip(*a)[0]), if you definitely need a list and not a
tuple)


/W

-- 
INVALID? DE!




More information about the Python-list mailing list