Is there a better way to chose a slice of a list?

Piet van Oostrum piet at cs.uu.nl
Wed May 20 07:08:22 EDT 2009


>>>>> walterbyrd <walterbyrd at iname.com> (w) wrote:

>w> On May 8, 5:55 pm, John Yeung <gallium.arsen... at gmail.com> wrote:
>>> On May 8, 3:03 pm,walterbyrd<walterb... at iname.com> wrote:
>>> 
>>> > This works, but it seems like there should be a better way.
>>> 
>>> > --------------
>>> > week = ['sun','mon','tue','wed','thu','fri','sat']
>>> > for day in week[week.index('tue'):week.index('fri')]:
>>> >    print day
>>> > ---------------
>>> 
>>> I think you should provide much more information, primarily why you
>>> want to do this.  What is the larger goal you are trying to achieve?

>w> I am just looking for a less verbose, more elegant, way to print a
>w> slice of a list. What is hard to understand about that? I am not sure
>w> how enumerated types help.

You didn't say that in the OP.

But you can extend the list type to accept slices with strings in them.
The language spec says they should be ints but apparently this is not
enforced. Of course this makes it vulnerable for future misbehaviour.

class KeyList(list):
    def __getitem__(self, indx):
        if isinstance(indx, slice):
            start = indx.start
            stop = indx.stop
            # add support for step if you want
            if not isinstance(start, int):
                start = self.index(start)
            if not isinstance(stop, int):
                stop = self.index(stop)
            return list.__getitem__(self, slice(start,stop))
        return list.__getitem__(self, indx)

week = KeyList(['sun','mon','tue','wed','thu','fri','sat'])
for day in week['tue':'fri']:
   print day

tue
wed
thu

Note that 'fri' is not included according to standard Python conventions
about the end of a slice. Change the code if you are not happy with it
and you don't mind getting inconsistent semantics.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list