How to treat the first or last item differently

Peter Otten __peter__ at web.de
Wed Jul 21 04:16:42 EDT 2010


Terry Reedy wrote:

> It makes sense to separate last detection from item processing so last
> detection can be put in a library module and reused.

Here's an extension of your idea that puts the detection of both the first 
and the last item into a generator:

def mark_first(items):
    items = iter(items)
    yield True, next(items)
    for item in items:
        yield False, item
    
def mark_last(items):
    items = iter(items)
    prev = next(items)
    for cur in items:
        yield False, prev
        prev = cur
    yield True, prev
        
def mark_ends(items):
    return ((head, tail, item) for head, (tail, item)
            in mark_first(mark_last(items)))

for items in "", "a", "ab", "abc":
    print list(items), "-->", list(mark_ends(items))

for first, last, item in mark_ends("abc"):
    if first:
        print "first",
    if last:
        print "last",
    print item

It may not be the most efficient approach, but it looks clean.



More information about the Python-list mailing list