Best way to check that you are at the beginning (the end) of an iterable?

Tim Chase python.list at tim.thechases.com
Wed Sep 7 20:01:33 EDT 2011


On 09/07/11 18:22, Laurent wrote:
> Anyway I was just asking if there is something better than
> enumerate. So the answer is no? The fact that I have to create
> a tuple with an incrementing integer for something as simple
> as checking that I'm at the head just sounds awfully
> unpythonic to me.

I've made various generators that are roughly (modulo 
edge-condition & error checking) something like

  def with_prev(it):
    prev = None
    for i in it:
      yield prev, i
      i = prev

  def with_next(it):
    prev = it.next()
    for i in it:
      yield prev, i
      prev = i
    yield prev, None

which can then be used something like your original

   for cur, next in with_next(iterable):
     if next is None:
       do_something_with_last(cur)
     else:
       do_regular_stuff_with_non_last(cur)

   for prev, cur in with_prev(iterable):
     if prev is None:
       do_something_with_first(cur)
     else:
       do_something_with_others(cur)

If your iterable can return None, you could create a custom 
object to signal the non-condition:

   NO_ITEM = object()

and then use NO_ITEM in place of "None" in the above code.

-tkc





More information about the Python-list mailing list