Indexing list of lists
__peter__ at web.de
Sat Sep 20 14:32:37 CEST 2003
Lukasz Pankowski wrote:
> Sorry for my misunderstanding, yes it would be nice to have a
> posibility to index a sequence with a list of indices, here is a pure
> Python (>= 2.2) implementation of the idea:
> class List(list):
> def __getitem__(self, index):
> if isinstance(index, (tuple, list)):
> return [list.__getitem__(self, i) for i in index]
> return list.__getitem__(self, index)
>>>> l = List(range(0, 100, 10))
> [0, 20, 30]
This is nice :-)
> but in this simple using both commas and slices will not work as
> [0, 10, [70, 80, 90]]
Your implementation can be extended to handle slices and still remains
def __getitem__(self, index):
if hasattr(index, "__getitem__"): # is index list-like?
result = 
for i in index:
if hasattr(i, "start"): # is i slice-like?
return list.__getitem__(self, index)
I have used hasattr() instead of isinstance() tests because I think that the
"we take everything that behaves like X" approach is more pythonic than
"must be an X instance".
While __getitem__() is fairly basic for lists, I am not sure if start can be
considered mandatory for slices, though.
More information about the Python-list