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

Rhodri James rhodri at wildebst.demon.co.uk
Tue May 19 19:22:12 EDT 2009


On Tue, 19 May 2009 22:38:19 +0100, walterbyrd <walterbyrd at iname.com>  
wrote:

> 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?
>
> 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? I am not sure
> how enumerated types help.

This is verbose and inelegant because of the way you're storing and
using the data, hence (I presume) John's question.  The more elegant
approach is not to try to index a list with strings, but to keep you
"day" data in numeric form and use that to slice with, and for that
enums will greatly help you keep things clear.  However, whether that's
worth doing or not depends on the bigger picture, and you haven't
told us anything that would help us figure that out.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list