How to access elemenst in a list of lists?

Terry Reedy tjreedy at udel.edu
Mon May 9 21:25:59 EDT 2011


On 5/9/2011 8:44 PM, Algis Kabaila wrote:

> The method of double indexing in the manner
> a[i][j]
> for the (i, j) -th element of multi-dimensional array is well known and
> widely used. But how to enable the "standard" matrix notation
> a[i, j]
> in Python 3.2 in the manner of numpy (and other matrix packages)? Is it
> subclassing of "special methods"
>
> __getitem__() # to get

> __setitem__()  # to set

Yes.

class listwrap:
     def __init__(self, lis):
         self._list = lis
     def __getitem__(self, dex):
         i,j = dex
         return self._list[i][j]
     # __setitem__: exercise for reader

l = listwrap([[1,2,3],['a','b','c']])
print(l[0,2],l[1,0])
# 3 a

IMO, Hardly worth it for two dimensions.
-- 
Terry Jan Reedy




More information about the Python-list mailing list