Search code examples
pythonpython-3.xiteratoryield-from

Remove consecutive duplicates from a list using yield generator?


i'm trying to compress a list using generator:

examples

[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]


ans = compress(test)
for x in ans:
    print(ans)

but i keep getting

generator object compress at 0x00000254D383C820. why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.


Solution

  • So there are several flaws, all of them described as comments to the question post.

    • there is a loop missing that would yield more than one value
    • you print ans and not x, which logically is the generator object.

    Is this code working for you?

    test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0]
    
    def compress(items):
        for i, d in enumerate(items[:-1]):
            if d == items[i+1]:
                continue
            yield d
        yield items[-1]
    
    for x in compress(test):
        print(x)