>>> pp = [('a',1),('b',1),('c',1),('d',2),('e',2)] >>> [[t1, t2] for ((t1, v1), (t2, v2)) in zip(pp, pp[1:]) if v1 != v2] [0] ['c', 'd'] >>>
I need this for clarity ... if you find that understanding the lists is understandable. It creates two temporary lists: pp [1:] and the result of zip (). Then he compares all neighboring pairs and gives the first change he discovered.
This similar generator expression does not create temporary lists and stops processing when it reaches the first change:
>>> from itertools import islice, izip >>> ([t1, t2] for ((t1, v1), (t2, v2)) in izip(pp, islice(pp, 1, None)) ... if v1 != v2 ... ).next() ['c', 'd'] >>>
All the examples on this page are more compact than if you wanted to catch errors.
source share