Indexing list of lists

Peter Otten __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]
>         else:
>             return list.__getitem__(self, index)
> 
>>>> l = List(range(0, 100, 10))
>>>> l[0,2,3]
> [0, 20, 30]

This is nice :-)

> but in this simple using both commas and slices will not work as
> expected
> 
>>>> l[0,1,7:]
> [0, 10, [70, 80, 90]]

Your implementation can be extended to handle slices and still remains
simple:

class List3(list):
    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?
                    result.extend(list.__getitem__(self, i))
                else:
                    result.append(list.__getitem__(self, i))
            return result
        else:
            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.

Peter




More information about the Python-list mailing list