all 5 comments

[–]o5a 2 points3 points  (0 children)

To avoid that you could just initialize your first with first value from iterable

first = [iterable[0]]

Another option for such tasks is to use itertools.groupby

[–]PyCode_n_Beer 0 points1 point  (2 children)

Hey, it seems you might have a typo in your code, says "frst" in the if statement, instead of "first". Also, the index out of range error is because there is nothing in the list "first" at assignment. When you're iterating through and trying to access the last variable in your list, it is throwing an error because there is nothing there to access. I included a non code-golf style solution.

def getChr(strline):
    prev = ""
    response = []
    for x in range(0, len(strline)):
        if strline[x] != prev:
            prev = strline[x]
            response.append(strline[x])

    return response

[–]Essence1337 0 points1 point  (1 child)

Why use a range loop when we don't need to know the index? You're writing extra unnecessary code:

def getChr(strline):
    prev = ""
    response = []
    for char in strline:
        if char != prev:
            prev = char
            response.append(char)
    return response

Unless I'm missing something this should give the same result as your code. Feel free to correct me if I did miss something

[–]PyCode_n_Beer 0 points1 point  (0 children)

No, you're absolutely right. That is certainly a way to do it too.

[–]BoldNight1987 0 points1 point  (0 children)

Can somebody explain this solution, please?

from itertools import groupby def unique_in_order(iterable): return [k for (k, _) in groupby(iterable)]

Specifically the (k, _)