[Tutor] Slices of lists of lists

Bob Williams linux at barrowhillfarm.org.uk
Fri Mar 28 11:09:20 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]
>    ...:   ]
> 
> 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]
> 
> In [4]: l[1][:]
> Out[4]: [21, 22, 23]
> 
> Again, fine! But what if we want to access a particular row? My first
> guess was that standard slice notation on the first index would do it,
> but it doesn't! Instead, we get the rows again:
> 
> In [6]: l[:][0]
> Out[6]: [11, 12, 13]
> 
> In [7]: l[:][1]
> Out[7]: [21, 22, 23]
> 

Jose,

Just for clarity, are you trying to access a particular *column* in your
last example?

Bob
-- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.3
Uptime:  06:00am up 4 days 19:51, 4 users, load average: 0.37, 0.18, 0.15


More information about the Tutor mailing list