On Fri, Mar 5, 2010 at 10:48 PM, Hugo Arts <hugo.yo...@gmail.com> wrote: > > Except the OP requested pairs (1, 2), (3, 4), i.e. with no duplicate > elements. Here is a generator that does what you need: > > def pairs(seq): > it = iter(seq) > try: > while True: > yield it.next(), it.next() > except StopIteration: > return > > Hugo >
Just Noticed this tiny caveat: If the length of the sequence is uneven, the last element will not be yielded by this generator. Whether that's a problem, and if it is, how to handle it, depends on the application you're working with. I did make a tiny modification to yield the last element in a pair with None as the second value. The benefit is that it doesn't skip any values, but you'll need to handle the possible None value in your code. Of course, if you want a generator that yields consecutive pairs, passing it a sequence of uneven length is sort of problematic to begin with. So for most applications the simple version should be fine. def pairs(seq): it = iter(seq) try: while True: a = it.next() b = it.next() yield a, b except StopIteration: if len(seq) % 2: yield a, None It's not as pretty as the simple version, unfortunately. in my experience, corner cases are rarely handleable by elegant code :( Compare output of the first and second version: >>> # first (elegant) version of pairs >>> list(pairs(range(5))) [(0, 1), (2, 3)] >>> # second version >>> list(pairs_2(range(5))) [(0, 1), (2, 3), (4, None)] _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor