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

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue May 19 22:26:10 EDT 2009


On Tue, 19 May 2009 14:38:19 -0700, 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. What is hard to understand about that? I am not sure how
> enumerated types help.

Printing a slice of a list is about as concise and elegant as possible:

print alist[slice_obj]

or

print alist[start:end:step]

But that's not what the example in your first post suggests. Your example 
suggests you have *two* problems:

(1) Given a slice, how to print each item in the slice _individually_.

The answer to that is 

for x in aslice:
    print x

Pretty concise and elegant.



(2) Given an arbitrary starting and ending _item_ rather than _position_, 
how to concisely and elegantly generate a slice.

There are many answers, depending on _why_ you want to do this. One 
possible answer is to write a function to do it:

def print_slice(alist, start_item, end_item):
    start_pos = alist.index(start_item)
    end_pos = alist.index(end_item)
    for x in alist[start_pos:end_pos]:
        print x

Now print_slice(week, 'tue', 'fri') is pretty concise and elegant.

Another answer is: Don't do that, do something else. If you have an 
enumerated type, then you could (in principle) do this:

week = enumerated('mon tue wed thu fri sat sun')
for x in week.tue-week.fri:
    print x


depending on the enumerated type itself naturally.



-- 
Steven



More information about the Python-list mailing list