2

I'm trying to figure out how to make sure that the consecutive values are not the same in a list. Expected output: [1, 2, 3] Actual output: [1, 1, 3, 3]

I also tried using next() but that gave me "list object is not an iterator"

What is best practices here and what am I doing wrong?

def unique_in_order(iterable):

    return [x for x in iterable if not iterable[x] == iterable[x+1]]

print(unique_in_order([1,1,2,2,3,3]))
1
  • for x in iterable here x is the values in the list not the index Commented Nov 22, 2022 at 13:58

5 Answers 5

2

Do it without list comprehensions. Create a list with the first element and iterate over the following pairs

def unique_in_order(iterable):
    lst = [iterable[0]]
    for x in range(len(iterable) - 1):
        if iterable[x] != iterable[x + 1]:
            lst.append(iterable[x + 1])
    return lst

you can also use zip

def unique_in_order(iterable):
    lst = [iterable[0]]
    for x, y in zip(iterable, iterable[1:]):
        if x != y:
            lst.append(y)
    return lst
Sign up to request clarification or add additional context in comments.

Comments

0

If you do it without a list comprehension, you can get better control flow and solve your problem:

def unique_in_order(iterable):
    list = []

    for index, x in enumerate(iterable):
        if index == len(iterable) -1:
            list.append(x)
        elif iterable[index] != iterable[index+1]:
            list.append(x)

    return list

Comments

0

Here's a way to do it using a generator. It assumes None is not the first value in the list.

def unique(lst):
    prev = None
    for val in lst:
        if val != prev:
            prev = val
            yield val

print(list(unique([1,1,2,2,3,3,1,1])))

1 Comment

You can use prev = object() as a sentinel value to make this work for iterables containing lists (assuming that there isn't a weird overriding of __eq__ somewhere).
0

You can use a list comprehension, but make sure to add the last element to the returned list.

def unique_in_order(lst):
    return [lst[i] for i in range(len(lst)-1) if lst[i] != lst[i+1]] + [lst[-1]]

Comments

0

The simplest way would be using itertools.groupby():

from itertools import groupby

def unique_in_order(iterable):
    return [i[0] for i in groupby(iterable)]

It will work for any iterable, not only lists.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.