[Tutor] Slices of lists of lists
Jose Amoreira
ljmamoreira at gmail.com
Fri Mar 28 10:42:29 CET 2014
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]
Why is this so?
Thanks,
Jose Amoreira
More information about the Tutor
mailing list