Steven Bethard <[EMAIL PROTECTED]> wrote: > Here's a solution that works for iterables other than lists: > > py> def collapse(iterable): > ... enumeration = enumerate(iterable) > ... _, lastitem = enumeration.next() > ... yield lastitem > ... for i, item in enumeration: > ... if item != lastitem: > ... yield item > ... lastitem = item > ... > py> lst = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5] > py> list(collapse(lst)) > [0, 1, 2, 3, 2, 4, 5] > > Again, I'm still not sure I'd call this more elegant...
Hmmmm, what role does the enumeration play here? I don't see how you're using it, at all. Why not just: def collapse(iterable): it = iter(iterable) lastitem = it.next() yield lastitem for item in it: if item != lastitem: yield item lastitem = item that's basically just the same as your code but without the strangeness of making an enumerate for the purpose of ignoring what the enumerate adds to an ordinary iterator. Alex -- http://mail.python.org/mailman/listinfo/python-list