I don't know anything built-in, but you can easily write a generator to provide the necessary information:
def firstlast(seq): seq = iter(seq) el = prev = next(seq) is_first = True for el in seq: yield prev, is_first, False is_first = False prev = el yield el, is_first, True >>> list(firstlast(range(4))) [(0, True, False), (1, False, False), (2, False, False), (3, False, True)] >>> list(firstlast(range(0))) [] >>> list(firstlast(range(1))) [(0, True, True)] >>> list(firstlast(range(2))) [(0, True, False), (1, False, True)] >>> for count, is_first, is_last in firstlast(range(3)): print(count, "first!" if is_first else "", "last!" if is_last else "") 0 first! 1 2 last!
source share