Question on lists
Andrew Bennetts
andrew-pythonlist at puzzling.org
Tue Jul 27 23:44:28 EDT 2004
On Wed, Jul 28, 2004 at 03:26:54AM +0000, Kristofer Pettijohn wrote:
> My question is about lists:
>
> Is there a way to remove duplicate items from a list that are
> next to each other?
>
> Example...
>
> Performing the operation on ['a', 'b', 'c', 'c', 'd', 'd', 'd', 'e']
> will return ['a', 'b', 'c', 'd', 'e']
>
> Performing the operation on ['a', 'b', 'c', 'c', 'd', 'c', 'd', 'e']
> will return ['a', 'b', 'c', 'd', 'c', 'd', 'e']
>
> I'm guessing there is probably nothing internal that will do it, so
> I may have to write something on my own - just thought I'd check
> first ;)
Nothing builtin that I know of, but it's trivial to write:
def uniq(iterable):
"""Remove consecutive duplicates from a sequence."""
prev = object()
for element in iterable:
if element != prev:
prev = element
yield element
>>> list(uniq(['a', 'b', 'c', 'c', 'd', 'd', 'd', 'e']))
['a', 'b', 'c', 'd', 'e']
>>> list(uniq(['a', 'b', 'c', 'c', 'd', 'c', 'd', 'e']))
['a', 'b', 'c', 'd', 'c', 'd', 'e']
-Andrew.
More information about the Python-list
mailing list