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

Rich picture Rich · Nov 20, 2013 · Viewed 9.7k times · Source

I'm trying to perform checks on the first and last elements of an interator. It has several thousand entries, so I need an expeditious method of checking. If found this post, that put me onto this strategy.

first = True
for value in iterator:
   if first:
      do_stuff_to_first_iter
      first = False
   else:
      pass
do_stuff_to_last_iter

Anyone have any opinions on a quicker method of accomplishing this? Thanks a lot!

Answer

Martijn Pieters picture Martijn Pieters · Nov 20, 2013

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.