Here is a version based on Karl that does not require copies of the list ( tmp , snippets, and zipped list). izip significantly faster than (Python 2) zip for large lists. chain bit slower than slicing, but does not require a tmp object or copy of a list. islice plus creating tmp slightly faster, but requires more memory and less elegant.
from itertools import izip, chain [y for x, y, z in izip(chain((None, None), li), chain((None,), li), li) if x != y != z]
Test
A timeit shows that it is about twice as fast as Karl or my fastest groupby version for short groups.
Be sure to use a value other than None (e.g. object() ) if your list may contain None s.
Use this version if you need it to work on an iterator / iterable that is not a sequence, or your groups are long:
[key for key, group in groupby(li) if (next(group) or True) and next(group, None) is None]
timeit shows it about ten times faster than another version for 1000 element groups.
Previously slow versions:
[key for key, group in groupby(li) if sum(1 for i in group) == 1] [key for key, group in groupby(li) if len(tuple(group)) == 1]
source share