I am trying to write a function that will test whether or not a list is in decending order. This is what I have so far, but it doesn\'t seem to be working for all lists. <
You can do this easily with a generator expression and the all() builtin:
all(earlier >= later for earlier, later in zip(seq, seq[1:]))
For example:
>>> seq = [9, 8, 5, 1, 4, 3, 2]
>>> all(earlier >= later for earlier, later in zip(seq, seq[1:]))
False
>>> seq = [9, 8, 5, 4, 3, 2]
>>> all(earlier >= later for earlier, later in zip(seq, seq[1:]))
True
This should be nice and fast as it avoids python-side loops, short circuits nicely (if you use itertools.izip() in 2.x), and is nice and clear and readable (avoiding looping over indices, for example).
Note that a generic solution for all iterators (not just sequences) is possible too:
first, second = itertools.tee(iterable)
next(second)
all(earlier >= later for earlier, later in zip(first, second))