[Tutor] Slices of lists of lists

Alan Gauld alan.gauld at btinternet.com
Fri Mar 28 11:32:26 CET 2014


On 28/03/14 09:42, Jose Amoreira wrote:
> Hello!
> Here is something that surprised me and I still didn't get it.
>
> If we want to store a matrix in pure python (no numpy), the first thing
> that comes to (my) mind is to use a list of lists, like the list l below:
> In [1]: l=[
>     ...:    [11,12,13],
>     ...:    [21,22,23]
>     ...:   ]
>

But remember this is not actually a two dimensional
table it is a sequential list of lists.
So Python sees it like:

 > In [1]: l=[[11,12,13],[21,22,23]...]

> We can access individual components of this object in a simple, to be
> expected way:
>
> In [2]: l[0][1], l[1][0]
> Out[2]: (12, 21)
>
> OK, that's fine. If we want to access individual rows of this matrix
> like object, the standard slice notation (on the second index) works as
> expected also:
>
> In [3]: l[0][:]
> Out[3]: [11, 12, 13]

The slice notation makes a copy. You don;t need that you can just use 
the first index:

In [3]: l[0]
Out[3]: [11, 12, 13]

> Again, fine! But what if we want to access a particular row?

I assume you mean column?
That concept doesn't exist, instead you must ask Python
for the n-th element of every sublist.

That's not too hard using a list comprehension:

 >>> [row[0] for row in l]
[11, 21]

> guess was that standard slice notation on the first index would do it,

No, standard slices on the first element will give you sublists of the 
first row. Python doesn't have any concept of that second dimension, it 
only sees a list of items. The fact those items are themselves lists is 
purely incidental to the interpreter.


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list