How about using iter and consuming the first item?
Edit: Returning to the OP question, there is a general operation that you want to perform for all elements, and then one operation that you want to perform for the first element and the other for the rest.
If this is just one function call, I would just write it twice. It will not end the world. If it is more active, you can use the decorator to wrap your “first” function and “rest” with a general operation.
def common(item): print "common (x**2):", item**2 def wrap_common(func): """Wraps `func` with a common operation""" def wrapped(item): func(item) common(item) return wrapped @wrap_common def first(item): """Performed on first item""" print "first:", item+2 @wrap_common def rest(item): """Performed on rest of items""" print "rest:", item+5 items = iter(range(5)) first(items.next()) for item in items: rest(item)
Output:
first: 2 common (x**2): 0 rest: 6 common (x**2): 1 rest: 7 common (x**2): 4 rest: 8 common (x**2): 9 rest: 9 common (x**2): 16
or you can make a fragment:
first(items[0]) for item in items[1:]: rest(item)
Ryan Ginstrom Dec 18 '09 at 12:37 2009-12-18 12:37
source share