Slice a list of lists?

Robert Kern robert.kern at gmail.com
Wed Sep 8 17:26:15 EDT 2010


On 9/8/10 3:27 PM, Terry Reedy wrote:
> On 9/8/2010 2:55 PM, Jonno 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]?
>
> You are trying to look at a list of lists as an array and have discovered where
> the asymmetry of the former makes the two non-equivalent. To slice
> multi-dimensional arrays any which way, you need an appropriate package, such as
> numpy.

A motivating example:

[~]
|1> import numpy

[~]
|2> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])

[~]
|3> a

array([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])

[~]
|4> a[0,2]
3

[~]
|5> a[2,0]
7

[~]
|6> a[0,:]
array([1, 2, 3])

[~]
|7> a[:,0]
array([1, 4, 7])


-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list