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

Terry Reedy tjreedy at udel.edu
Tue May 19 19:21:52 EDT 2009


walterbyrd 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. 

week[2:5] # ;-)

If you want the interpreter to turn non-ints into ints for you, you will 
have to give it some sort of function or mapping to use.

dayint = {day:i for i,day in enumeratr(week)} # works in Py3 at least
week[dayint['tue']:dayint['fri']]

# or, untested, basing attrodic on memory of posted code

class attrodic(): #py3
   def __init__(self, dic):
     self.__dict__.update(dic)

di = attrodic(week)
week[di.tue:di.fri]

Most elegant, and most setup work ;-).

Terry Jan Reedy




More information about the Python-list mailing list