Skip to content

Instantly share code, notes, and snippets.

@dansondergaard
Last active October 10, 2017 13:38
Show Gist options
  • Select an option

  • Save dansondergaard/e239e478e757c1e2ce378fd18ca8289f to your computer and use it in GitHub Desktop.

Select an option

Save dansondergaard/e239e478e757c1e2ce378fd18ca8289f to your computer and use it in GitHub Desktop.
from itertools import zip_longest
def remove_consecutive(lst, item=0):
"""Remove consecutive occurrences of `item` from `lst`.
For example:
>>> print(list(remove_consecutive([1, 1, 0, 0, 0, 1, 0, 1, 1], item=0)))
[1, 1, 0, 1, 0, 1, 1]
>>> print(list(remove_consecutive(['a', 'b', '', '', '', 'c', '', 'd', 'e'], item='')))
['a', 'b', '', 'c', '', 'd', 'e']
Single occurrences will always be kept.
"""
return (a for a, b in filter(lambda x: x != (item, item), zip_longest(lst[0:], lst[1:])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment