«
Comparing iterables
»
Python doesn't have a way to compare arbitrary iterables (without converting them to a tuple or list). It's also easy to get it wrong if you try and do it with itertools (since imap and izip will consume an extra element from the first sequence if it's longer). Here's how to do it right:
from itertools import ifilter, imap, chain class StopToken: def __cmp__(self, other): if self is other: return 0 return -1 StopToken = StopToken() def cmpseq(a, b, StopToken=StopToken): a, b = chain(a, (StopToken,)), chain(b, (StopToken,)) for rval in ifilter(None, imap(cmp, a, b)): return rval try: a.next() return 1 except StopIteration: try: b.next() return -1 except StopIteration: return 0