Max Andersson
Max Andersson

Reputation: 135

Comparing next element in a list Python

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]))

Upvotes: 2

Views: 718

Answers (5)

bereal
bereal

Reputation: 34281

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.

Upvotes: 0

CodeKorn
CodeKorn

Reputation: 298

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]]

Upvotes: 0

Kurt
Kurt

Reputation: 1748

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])))

Upvotes: 0

Marcello Zago
Marcello Zago

Reputation: 726

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

Upvotes: 0

Guy
Guy

Reputation: 50819

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

Upvotes: 2

Related Questions