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

John Machin sjmachin at
Tue May 19 19:59:47 EDT 2009

On May 20, 7:38 am, walterbyrd <walterb... at> wrote:
> On May 8, 5:55 pm, John Yeung <gallium.arsen... at> wrote:
> > On May 8, 3:03 pm,walterbyrd<walterb... at> wrote:
> > > This works, but it seems like there should be a better way.
> > > --------------
> > > ---------------
> > 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?
> I am just looking for a less verbose, more elegant, way to print a
> slice of a list. What is hard to understand about that?

Ummm two things, (1) You didn't say that was what you wanted (2) It's
a nonsense anyway:

Your original statement "choose a slice of alist": answer = alist

Your current statement "print a slice of a list" (one element per line
as per your example): can not be done much less verbosely and more
elegantly than:
    for x in alist[lo:hi]:
        print x

Your real problem appears to be the horrid method of deriving lo and

You gave ONE example without stating anything more precise than that
it was an example of a slice of a list [which was obvious anyway] and
didn't specify in what sense of "better" you wanted a better way. So
people have to guess what you really want.

Guessing that the 'tue' and 'fri' in your one example will always be
constants, here are two options:

E.g. given
week = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']

Option (1):
SUN, MON, TUE, WED, THU, FRI, SAT = range(7)
for day in week[TUE:FRI]:
    print day

Option (2):
for day in week[2:5]:
    print day


More information about the Python-list mailing list