Slice a list of lists?

J

Jonno

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]?
 
A

Andreas Waldenburger

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
 
A

Andreas Waldenburger

Let me rephrase what I wrote a bit.

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

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

I hope this is a little less confusing.

/W
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top