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


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to