Fastest way to get the first and last element of a python iterator

Get the first value with the next() function:

first = last = next(iterable, defaultvalue)
for last in iterable:
    pass

This assumes the iterable is finite.

For an empty iterable, first and last are set to defaultvalue. For an iterable with just one element, first and last will both refer to that one element. For any other finite iterable, first will have the first element, last the very last.


Based on my answer to the linked question:

Probably worth using __reversed__ if it is available. If you are providing the iterator, and there is a sensible way to implement __reversed__ (ie without iterating from end to end) you should do it

first = last = next(my_iter)
if hasattr(my_iter,'__reversed__'):
    last = next(reversed(my_iter))
else:
    for last in my_iter:
        pass